Exceptions - How do you make it work like built-in exceptions?

Chris cwitts at gmail.com
Sun Jan 13 15:46:33 CET 2008


On Jan 13, 4:14 pm, Lie <Lie.1... at gmail.com> wrote:
> A built-in exceptions, when raised, would print traceback that points
> out the offending code, like this:
>
> Traceback (most recent call last):
>   File "F:\dir\code.py", line 43, in <module>
>     a = 1/0 <<<---
> ZeroDivisionError: integer division or modulo by zero
>
> a user-made exception, when raised, would print traceback that points
> out the code that raises the exception
>
> Traceback (most recent call last):
>   File "F:\dir\code.py", line 48, in <module>
>     raise SomeException('Some Exception Message') <<<---
> SomeException: Some Exception Message
>
> which is generally of little use (yeah, it's possible to trace the
> code from the line number, but sometimes it might not be that easy,
> cause the line number is (again) the line number for the raising code
> instead of the offending code)
>
> The sample exception was generated from this code:
> ####
> class SomeException(Exception):
>     pass
>
> try:
>     a = 1/0
> except:
>     raise SomeException('Some Exception Message')
> ####
>
> Is it possible to make the user-made exception points out the
> offending code?

from sys import exc_info

try:
    a = 1/0
except:
    type, value, traceback = exc_info()
    raise SomeException(type)



More information about the Python-list mailing list