Exception Handling
There are two distinguishable kinds of errors in Python. One is syntax error, caused by malformed Python code. This kind of error is typically detected immediately before the program starts executing. The other kind of error is known as an exception. It is generated during program execution in response to an unexpected condition. For example, if we divide a number by 0, we get an error like this:
Or if we open a nonexistent file for reading, an exception is generated.
In Python, exceptions are objects that are generated at the time of an error, which can then be passed on to error handling code. In the absence of explicit error handling code, in the form of try and except blocks, the default response to an exception is to print it to the screen and terminate the program.
Exception handling
It is possible to write programs that handle selected exceptions. We use the try statement to execute the code that might generate error(s) that we want to catch. Specific error conditions can then be tested for and responded to, using one or more except statements. The try and except statements work as follows.
- First, the code block between the try and except keywords is executed.
- If no exception occurs, any except statements and their code blocks are skipped, and execution continues.
- If an exception occurs during execution of the try, the rest of the statements in its code block are skipped. Then the except statements are checked one at a time, in order, to see if one matches the specific exception. If there is a match to the exception named after one of the except keywords, the code block following that except is executed, and then execution returns to the try statement and continues from there.
- If an exception occurs which does not match the exception named in any except statement, it is passed on to outer try statements; if no except handler is found, it is an unhandled exception and execution stops with a message as shown above.
Let’s look at an example.
In the example above, the ValueError exceptions occur when the attempt to construct an int from the input string fails. Curiously, while it is possible to construct an int from the float 13.5 (with the result being the int 13), it is not possible to construct an integer from the string "13.5".
The raise statement
The raise statement allows a programmer to force a specific exception to occur. It works in conjunction with an object of the Exception class (or a class that derives from it, like StandardError—these classes are generally defined in the exceptions module.) The object will often be given a message attribute containing the error string that the programmer wants to appear when the exception is raised. For example:
Note that a suitable Exception object can be created ahead of time, or it can be instantiated “on the fly”, simply by calling its constructor immediately after the raise keyword.
Built-in exceptions
Many of Python’s built-in exceptions are self-explanatory. Here are some of the more commonly encountered ones.
- NameError - You probably misspelled a variable or function name, or you otherwise referenced a name that was never defined.
- IOError - I/O operation failed.
- SystemError - Internal error in the Python interpreter.
- ZeroDivisionError - Second argument to a division or modulo operation was zero.