Differences between revisions 3 and 4
Revision 3 as of 2003-11-21 19:33:55
Size: 833
Editor: ip503dabc3
Comment: don't *ever* use a too general exception class, CatchWhatYouCanHandle
Revision 4 as of 2003-11-21 22:14:02
Size: 875
Editor: dsl254-010-130
Comment: To do: Write about how to capture catch-all "Exception"
Deletions are marked like this. Additions are marked like this.
Line 30: Line 30:
Give example of multiple excepts. Handling multiple excepts in one line. Give example of multiple excepts. Handling multiple excepts in one line. Catch-all "Exception" exception handling.

Handling Exceptions

The simplest way to handle exceptions is with a "try-except" block:

   1 (x,y) = (5,0)
   2 try:
   3   z = x/y
   4 except ZeroDivisionError:
   5   print "divide by zero"

If you wanted to examine the exception from code, you could have:

   1 (x,y) = (5,0)
   2 try:
   3   z = x/y
   4 except ZeroDivisionError, e:
   5   z = e # representation: "<exceptions.ZeroDivisionError instance at 0x817426c>"
   6 print z # output: "integer division or modulo by zero"

To Write About...

Give example of IOError, and interpreting the IOError code.

Give example of multiple excepts. Handling multiple excepts in one line. Catch-all "Exception" exception handling.

Show how to use "else" and "finally".

Show how to continue with a "raise".

See Also:

WritingExceptionClasses, TracebackModule, CoupleLeapingWithLooking

HandlingExceptions (last edited 2020-09-14 13:35:48 by MatsWichmann)

Unable to edit the page? See the FrontPage for instructions.