Introducing Python © Chirag Wazir 2002 Prev   Index   Next

Exceptions

1/0
    Traceback (most recent call last):
      File "", line 1, in ?
        1/0
    ZeroDivisionError: integer division or modulo by zero

Handling Exceptions:

while 1:
     try:
         x = int(raw_input("Please enter a number: "))
         break
     except ValueError:
         print "Oops! That was no valid number.  Try again..."
Please enter a number: hello
Oops! That was no valid number.  Try again...
Please enter a number: 15
except (RuntimeError, TypeError, NameError):
except IOError, (errno, strerror):

The raise statement allows the programmer to force a specified exception to occur.

The try ... except statement has an optional else clause, which is useful for code that must be executed if the try clause does not raise an exception.

The optional finally clause is intended to define clean-up actions that must be executed under all circumstances.

A try statement must either have one or more except clauses or one finally clause, but not both.

User-defined exceptions can be derived from the Exception class.