2

I am newbie to python . I know how to raise a **custom exception** in python with a message printed on to the stdout. But when I am dealing with multiple modules and long codes, while raising an exception with a message , can I trace back as well? what I meant as trace back is get the error line , or say the function and module name where the exception happened ?? I know that the message that I am giving out can be modified in such a way that I add more detail information. But I was wondering if there is any inbuilt way of doing this.

Krishna
  • 131
  • 2
  • 11

2 Answers2

3

You don't have to "generate" a traceback, Python takes care of this when you raise an exception (custom or builtin).

Python 2.7.3 (default, Feb 27 2014, 19:58:35) 
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
pythonrc start
pythonrc done
>>> class MyException(Exception): pass
... 
>>> def foo():
...     raise MyException("Hey")
... 
>>> def bar():
...    print "in bar"
...    foo()
... 
>>> bar()
in bar
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 3, in bar
  File "<stdin>", line 2, in foo
__main__.MyException: Hey
>>> 
bruno desthuilliers
  • 75,974
  • 6
  • 88
  • 118
-2

This question is been already answered here:

Quoting the response there from Glenn Maynard:

It's simple; pass the traceback as the third argument to raise.

import sys
class MyException(Exception): pass

try:
    raise TypeError("test")
except TypeError, e:
    raise MyException(), None, sys.exc_info()[2]

Always do this when catching one exception and re-raising another.

Community
  • 1
  • 1
Aitor Martin
  • 724
  • 1
  • 11
  • 26
  • This is not an appropriate way to handle duplicate questions. You need a rep of 3k to cast close votes, but you already have enough rep to flag the question and add a comment with a link to the dupe. – jonrsharpe Jul 18 '14 at 12:29
  • Also, there were better answers to the duplicated question (at least now there is..) – Kaos Nov 12 '20 at 10:37