Search code examples
pythonexceptiontraceback

In Python how can I raise a custom exception and do a trace back as well?


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.


Solution

  • 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
    >>>