|
Data Structures and Algorithms
with Object-Oriented Design Patterns in Python |
Sometimes unexpected situations arise during the execution of a program. Careful programmers write code that detects errors and deals with them appropriately. However, a simple algorithm can become unintelligible when error-checking is added because the error-checking code can obscure the normal operation of the algorithm.
Exceptions provide a clean way to detect and handle unexpected situations. When a program detects an error, it raises an exception. When an exception is raised, control is transfered to the appropriate exception handler . By defining a method that catches the exception, the programmer can write the code to handle the error.
In Python, an exception is an object.
All exceptions in Python are ultimately derived from the built-in
base class called Exception.
For example,
consider the class A defined in Program
.
Since the A class extends the Exception class,
A is an exception that can be raised.

Program: Using exceptions in Python.
A method raises an exception by using the raise statement:
The raise statement is similar to a return statement.
A return statement represents the normal termination
of a method and the object returned matches the return value of the method.
A raise statement represents the abnormal termination of a method
and the object raised represents the type of error encountered.
The f method in Program
raisess an A exception.
Exception handlers are defined using a try block: The body of the try block is executed either until an exception is raised or until it terminates normally. One or more exception handlers follow a try block. Each exception handler consists of an except clause which specifies the exceptions to be caught, and a block of code, which is executed when the exception occurs. When the body of the try block raises an exception for which an exception is defined, control is transfered to the body of the exception handler.
In this example, the exception raised by the f method is caught by the g method. In general when an exception is raised, the chain of methods called is searched in reverse (from caller to callee) to find the closest matching except clause. When a program raises an exception that is not caught, the program terminates.