catching all exceptions

Steve Holden sholden at holdenweb.com
Thu Feb 8 10:11:50 EST 2001


<nospam at our.site> wrote in message news:95uati$cm4$1 at icrf.news...
> This message has been posted by:  Arne Mueller
<a.mueller at REMOVE-THIS-TO-SENDicrf.icnet.uk>
>
> Hi All,
>
> I'm (still) using python 1.5.2 and I'd like to catch all exceptions in a
> try block then find out what kind of exception excatly was risen and
> save the output that would have been produced if I hadn't cought the
> exception (or the stack-trace up to this position). Something like this:
>
> try:
>     do_something()
> except (IOError, ...), value:
>     this_exception = Exception_class
>     ...
>     write_Exception_to_database(this_exception, value)
>     raise this_exception, value
>
In general, of course, you can't be sure whether there is additional
information in the exception, since that depends entirely on how it was
raised (and I don't mean were its parents kind to it).

You presumably realisethat you can catch all exceptions with a simple
"except:" clause?

> The thing is that my program may raise all kinds of exceptions (not only
> user defined exceptions), and I'd like to write the exception class (not
> the Exceptions base class), the value, and the stack-trace up to this
> point as one big string to a database before terminating the program.
>
> currently I'm doing:
>
> try:
>   do_something()
> except Exceptions, value:
>   write_Exception_to_database('Python-Error: ' + repr(value))
>   sys.exit(-1)
>
> with this I think I can catch all predefined exception classes, because
> Exceptions is the base class for all other exceptions, but I realy want
> to know which derived exception class was raised (and also the
> stack-trace).
>
Exceptions defined by library modules *should* define their exceptions as
Exception subclasses, but there is no guarantee they will. Hence the value
of the "except:" clause, which guarantees to catch everything (including
SystemExit and KeyboardInterrupt, so you have to be careful...).

> Is there (simple) way to do that in python (1.5.2)?
>
try:
    some extremely hairy code
except:
    report as effectively as possible on the exception
    raise # re-raise it for outer except clauses to deal with

> thanks alot for help,
>
> Arne
>
The "raise" statement with no exception specifications simply passes the
same exception up to whatever is waiting "above" to deal with it, ultimately
resulting in an interpreter error message if nothing else is available.

regards
 Steve




More information about the Python-list mailing list