Differences between revisions 1 and 6 (spanning 5 versions)
Revision 1 as of 2003-11-17 20:12:31
Size: 522
Editor: dsl254-010-130
Comment: A little something to get the ball rolling.
Revision 6 as of 2003-11-22 00:01:59
Size: 1227
Editor: ip503dabc3
Comment: catch-all bad! ;)
Deletions are marked like this. Additions are marked like this.
Line 10: Line 10:
except ZeroDivisionError:
  print "divide by zero"
}}}

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

{{{
#!python
(x,y) = (5,0)
try:
  z = x/y
except ZeroDivisionError, e:
  z = e # representation: "<exceptions.ZeroDivisionError instance at 0x817426c>"
print z # output: "integer division or modulo by zero"
}}}

This page previously used a catch-all exception clause:

{{{
#!python
(x,y) = (5,0)
try:
  z = x/y
Line 11: Line 34:
  z = "divide by zero"   print "divide by zero"
Line 13: Line 36:

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!

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"

This page previously used a catch-all exception clause:

   1 (x,y) = (5,0)
   2 try:
   3   z = x/y
   4 except:
   5   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!

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

HandlingExceptions (last edited 2024-03-05 20:29:39 by MatsWichmann)

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