How to except the unexpected?

Steven D'Aprano steve at REMOVETHIScyber.com.au
Sat Mar 4 20:47:33 EST 2006


On Sat, 04 Mar 2006 13:19:29 -0800, James Stroud wrote:

> Why catch an error only to re-raise it?

As a general tactic, you may want to catch an exception, print extra
debugging information, then raise the exception again, like this:

try:
    x = somedata()
    y = someotherdata()
    z = process(x, y)
except Exception:
    print "Error!"
    print "Value of x: %s" % x
    print "Value of y: %s" % y
    raise


Although that's not the reason the Original Poster is doing this.

The OP is doing it because catching all exceptions masks bugs. There are
certain exceptions which should be allowed through, as they indicate a bug
in the OP's code. Normally the tactic is to catch only the exceptions you
are interested in, and let everything else through, but the OP needs to
catch all exceptions because there are rare exceptions which he can't
predict in advance.



-- 
Steven.




More information about the Python-list mailing list