catching all exceptions

Bengt Richter bokr at oz.net
Sat Aug 13 20:01:10 CEST 2005


On Sat, 13 Aug 2005 17:42:00 +0200, a_geek at web.de wrote:

>Hello,
>
>I'd like to catch all exeptions and be able to inspect them.
>
>The simple case: I know which exceptions I'll get:
>
># standard textbook example:
>try:
>    something()
>except ThisException, e:
>    print "some error occurred: ", str(e)
>
>
>The not-so-simple case: Handling all other exceptions:
>
># nice-to-have:
>try:
>    something()
>except *, e:
>    print "some error occurred: ", type(e), str(e)
>
>
>Well, actually the second statement doesn't even compile... any ideas
>why I shouldn't be able to catch "anonymous" exceptions like this, or
>whether and how I can (and only overlooked it)?
>
>
>TIA!
>

 >>> def test(something):
 ...     try:
 ...         something()
 ...     except Exception, e:
 ...         print '%s: %s'% (e.__class__.__name__, e)
 ...
 >>> test(lambda: 1/0)
 ZeroDivisionError: integer division or modulo by zero
 >>> test(lambda: unk)
 NameError: global name 'unk' is not defined
 >>> test(lambda: open('unk'))
 IOError: [Errno 2] No such file or directory: 'unk'

All exceptions should derive from Exception, so the above should catch them,
although there are deprecated string exceptions that will not be caught.
You can catch these with a bare except, but it is probably better not to,
so you will know there's something to clean up.

If you do have to deal with them, you can then catch them by name individually,
or all with the bare except, e.g.,

 >>> def strexraiser(s): raise s
 ...
 >>> def test(something):
 ...     try:
 ...         something()
 ...     except Exception, e:
 ...         print '%s: %s'% (e.__class__.__name__, e)
 ...     except 'ugh':
 ...         print 'Caught "ugh"'
 ...     except:
 ...         print sys.exc_info()
 ...
 >>> import sys # forgot, will need when above executes ;-)
 >>>
 >>> test(lambda:strexraiser('ugh'))
 Caught "ugh"
 >>> test(lambda:strexraiser('gak'))
 ('gak', None, <traceback object at 0x02EF0ACC>)
 >>> test(lambda:1/0)
 ZeroDivisionError: integer division or modulo by zero

Regards,
Bengt Richter



More information about the Python-list mailing list