Size: 805
Comment: added "except Exception, e:" example.
|
Size: 1274
Comment: CatchWhatYouCanHandle
|
Deletions are marked like this. | Additions are marked like this. |
Line 10: | Line 10: |
except: z = "divide by zero" |
except ZeroDivisionError: print "divide by zero" |
Line 21: | Line 21: |
except Exception, e: | except ZeroDivisionError, e: |
Line 25: | Line 25: |
This page previously used a catch-all exception clause: {{{ #!python (x,y) = (5,0) try: z = x/y except: print "divide by zero" }}} This is bad because you'll almost certainly catch too many errors. As a simple example, when the user presses Ctrl-C, thus generating a KeyboardInterrupt, it will be caught and the code above will print "divide by zero". Now that's confusing, so you should only Wiki:CatchWhatYouCanHandle. |
Handling Exceptions
The simplest way to handle exceptions is with a "try-except" block:
If you wanted to examine the exception from code, you could have:
This page previously used a catch-all exception clause:
This is bad because you'll almost certainly catch too many errors. As a simple example, when the user presses Ctrl-C, thus generating a KeyboardInterrupt, it will be caught and the code above will print "divide by zero". Now that's confusing, so you should only CatchWhatYouCanHandle.
To Write About...
Give example of IOError, and interpreting the IOError code.
Give example of multiple excepts. Handling multiple excepts in one line.
Show how to use "else" and "finally".
Show how to continue with a "raise".
See Also:
WritingExceptionClasses, TracebackModule, CoupleLeapingWithLooking