Skip to content Skip to sidebar Skip to footer

Handling Exceptions In Python

What the best way of handling exceptions. class SRException(Exception): default_exception = True def somefun1(email): try: user = somefun2(email)

Solution 1:

Your exception handler is too broad, catch only the specific exceptions you know you can handle. There is no sense in catching an Exception only to wrap it in another exception and re-raising it; an exception object carries a Traceback that will show you what path the code is going. Just let the Exception bubble up, and catch it at a level where you can recover from the exception.

Solution 2:

It is usually not necessary to wrap exceptions at every level of the call stack. You are better off catching exceptions somewhere high up in the call stack and dumping a stack trace into the tech-support email. This will indicate quite clearly where the problem occurred and where it was called from.

With a bit of digging around in sys.exc_info()[2], you could even dump a complete list of parameters and locals in each stack frame, which would give support staff the offending email address.

Solution 3:

First of all, never just check for Exception! Always use the correct subtype you are actually expecting.

Also you shouldn't encapsulate already useful exceptions into other ones; and in general use the type of the exception as an identification of what happens. Then you can simply keep throwing (informative) exceptions at low level, and catch them all separately at a higher level to determine the correct error message for the end user.

Post a Comment for "Handling Exceptions In Python"