This section introduces methods for exception handling in Python.
Common Exceptions
Common exceptions in Python are listed in Table 12-1. Python assigns names to different types of errors. During programming, if an error occurs, it can be caught and checked whether it is a specified type of error, and corresponding handling can be performed.
Table 12-1 Common Exceptions in Python
| Exception | Description |
|---|---|
| ArithmeticError | Errors caused by arithmetic operations |
| FloatingPointError | Errors caused by floating-point calculations |
| OverflowError | Overflow errors caused by excessively large calculation results |
| ZeroDivisionError | Division by zero |
| AttributeError | Errors caused by failed attribute reference or assignment |
| BufferError | Errors caused when buffer-related operations cannot be performed |
| ImportError | Errors caused by failing to import a module/object |
| ModuleNotFoundError | No module found or None found in sys.modules |
| IndexError | Errors caused by the absence of an index in a sequence |
| KeyError | Errors caused by the absence of a key in a mapping |
Continued Table
| Exception | Description |
|---|---|
| MemoryError | Memory overflow error |
| NameError | Errors caused by an undeclared or uninitialized object |
| UnboundLocalError | Errors caused by accessing an uninitialized local variable |
| OSError | Operating system errors |
| FileExistsError | Errors caused by creating an existing file or directory |
| FileNotFoundError | Errors caused by using a non-existent file or directory |
| InterruptedError | Errors caused by a system call being interrupted by an input signal |
| IsADirectoryError | Errors caused by requesting file operations on a directory |
| NotADirectoryError | Errors caused by requesting directory operations on a non-directory object |
| TimeoutError | System-level timeout of system functions |
| RuntimeError | Runtime errors |
| SyntaxError | Syntax errors |
| SystemError | Internal errors found by the interpreter |
| TypeError | Object type errors |
Exception Handling: Single-Branch Case
In Python, the try...except...else...finally... structure is used to catch exceptions. Depending on needs, simple single-branch forms or multi-branch forms with else and finally can be used.
Below, the single-branch case is introduced. There are two syntax formats for single-branch exception handling.
The first format is as follows:
try:
<statement>
except:
print('Exception description')
The second format is as follows:
python
try:
<statement>
except <ExceptionName>:
print('Exception description')
The first format catches all errors, and the second format catches specified errors. Here, the try block executes the specified code normally, and the except block catches errors and performs related display and handling. Generally, avoid using the first format or handle unknown errors in multi-branch cases.
In the following code, the try block attempts to use a variable that is not declared or assigned. The except block catches the NameError type error and outputs it.
>>> try:
f
except NameError as e:
print(e)
Press Enter. Since an undeclared variable is used, the error "name 'f' is not defined" is caught, and the output is as follows:
name 'f' is not defined
Exception Handling: Multi-Branch Case
If the caught error may belong to multiple types, use the multi-branch form for handling. The syntax format for multi-branch exception handling is as follows:
try:
<statement>
except(<ExceptionName1>, <ExceptionName2>, ...):
print('Exception description')
The following code performs division. If an error occurs, it catches the "division by zero" error and the "variable not defined" error. The except statement specifies these two error names using a tuple and outputs the caught error result.
>>> b = 0
>>> try:
3 / b
except(ZeroDivisionError, NameError) as e:
print(e)
Press Enter. The caught error is as follows:
division by zero
Multi-branch error handling can also be written in the following form, judging in sequence:
try:
<statement>
except <ExceptionName1>:
print('Exception description 1')
except <ExceptionName2>:
print('Exception description 2')
except <ExceptionName3>:
print('Exception description 3')
Rewrite the above example code as follows:
>>> try:
3 / 0
except ZeroDivisionError as e:
print(e)
except NameError as e:
print(e)
Press Enter to get the same output result:
division by zero
Exception Handling: try…except…else…
Single-branch and multi-branch forms are used to catch and handle errors. How to handle cases where no error is caught? This uses the try…except…else… structure introduced in this section, as shown below. Here, the else block handles cases where no exception is found.
try:
<statement>
except <ExceptionName1>:
print('Exception description 1')
except <ExceptionName2>:
print('Exception description 2')
else:
<statement>
The following code calculates 3/2. If no error is caught, it outputs a series of equal signs.
>>> b = 2
>>> try:
3 / b
except(ZeroDivisionError, NameError) as e:
print(e)
else:
print('==========')
Press Enter. The calculation result is 1.5, no error is caught, so a series of equal signs is output:
1.5
==========
Exception Handling: try…finally…
The try...finally... structure executes the code in the finally block regardless of whether an exception occurs. Its syntax format is as follows:
try:
<statement>
finally:
<statement>
In the following example code, 3/0 is calculated. Since the divisor is 0, the except block catches the "division by zero" error and outputs the error information. However, even if an error occurs, the code in the finally block is executed for handling.
>>> try:
3 / 0
except ZeroDivisionError as e:
print(e)
finally:
print('Execute finally')
Press Enter. The output is as follows. The first line is the "division by zero" error information, and the second line is the output result of the finally block.
division by zero
Execute finally