Best Way to Handle All Exceptions

Ben Finney ben+python at benfinney.id.au
Tue Jul 14 02:59:07 EDT 2009


Steven D'Aprano <steven at REMOVE.THIS.cybersource.com.au> writes:

> Isn't that risky though? Won't that potentially change the exception-
> handling behaviour of functions and classes he imports from other
> modules?

No, any existing ‘except’ clause will be unaffected by re-binding
‘sys.excepthook’. As I understand the documentation, that function is
called only if the exception is uncaught by anything else.

    >>> 1 / 0
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    ZeroDivisionError: integer division or modulo by zero

    >>> import sys
    >>> def reverse_handler(exc_type, exc_instance, exc_traceback):
    ...     print exc_type.__name__[::-1], str(exc_instance)[::-1]
    ...
    >>> sys.excepthook = reverse_handler

    >>> try:
    ...     1 / 0
    ... except ZeroDivisionError:
    ...     print "You created a black hole."
    ... 
    You created a black hole.
    >>> 1 / 0
    rorrEnoisiviDoreZ orez yb oludom ro noisivid regetni

In other words, it is the function that (unless re-bound) prints the
traceback we're all familiar with when an exception is uncaught. It is
exposed via the name ‘sys.excepthook’ precisely for the purpose of
changing the default handler for uncaught exceptions

-- 
 \         “I have yet to see any problem, however complicated, which, |
  `\      when you looked at it in the right way, did not become still |
_o__)                                more complicated.” —Paul Anderson |
Ben Finney



More information about the Python-list mailing list