Exceptions

try-except

     try:
         f = open(filename)
         ...
     except IOError, e:
         print "Unable to open",filename,e
  • Different types of exceptions have names (e.g., "IOError")
  • If an exception of that type occurs in try-block, control passes to the matching except-block.
  • Exceptions have values. Placed into optional variable supplied to except.

raise

     raise ValueError, "Expected a positive value"
  • Raises an exception of a given type (e.g., "ValueError").
  • Accepts an optional value.
  • This value gets passed back to a matching except statement.
  • If exception is uncaught, program terminates with an error.
<<< O'Reilly OSCON 2000, Introduction to Python, Slide 69
July 17, 2000, beazley@cs.uchicago.edu
>>>