Python2.x Python Exception Handling
Python provides two very important features to handle exceptions and errors that occur during the execution of Python programs. You can use these features to debug Python programs.
- Exception handling: This site's Python tutorial will introduce in detail.
- Assertions: This site's Python tutorial will introduce in detail.
| Exception Name | Description |
|---|---|
| BaseException | Base class for all exceptions |
| SystemExit | Interpreter requests exit |
| KeyboardInterrupt | User interrupts execution (usually by inputting ^C) |
| Exception | Base class for regular errors |
| StopIteration | Iterator has no more values |
| GeneratorExit | Generator raises exception to notify exit |
| StandardError | Base class for all built-in standard exceptions |
| ArithmeticError | Base class for all numerical calculation errors |
| FloatingPointError | Floating point calculation error |
| OverflowError | Numerical operation exceeds maximum limit |
| ZeroDivisionError | Division (or modulo) by zero (all data types) |
| AssertionError | Assertion statement failed |
| AttributeError | Object does not have this attribute |
| EOFError | No built-in input, reached EOF marker |
| EnvironmentError | Base class for operating system errors |
| IOError | Input/output operation failed |
| OSError | Operating system error |
| WindowsError | System call failed |
| ImportError | Import module/object failed |
| LookupError | Base class for invalid data queries |
| IndexError | Sequence does not have this index |
| KeyError | Mapping does not have this key |
| MemoryError | Memory overflow error (not fatal to Python interpreter) |
| NameError | Undeclared/uninitialized object (no attribute) |
| UnboundLocalError | Accessing uninitialized local variable |
| ReferenceError | Weak reference attempts to access already garbage collected object |
| RuntimeError | General runtime error |
| NotImplementedError | Method not yet implemented |
| SyntaxError | Python syntax error |
| IndentationError | Indentation error |
| TabError | Mixed use of Tab and spaces |
| SystemError | General interpreter system error |
| TypeError | Invalid operation on type |
| ValueError | Invalid argument passed |
| UnicodeError | Unicode related errors |
| UnicodeDecodeError | Error during Unicode decoding |
| UnicodeEncodeError | Error during Unicode encoding |
| UnicodeTranslateError | Error during Unicode translation |
| Warning | Base class for warnings |
| DeprecationWarning | Warning about deprecated features |
| FutureWarning | Warning about constructions whose meaning will change in the future |
| OverflowWarning | Old warning about automatic promotion to long integer |
| PendingDeprecationWarning | Warning about features that will be deprecated |
| RuntimeWarning | Warning about suspicious runtime behavior |
| SyntaxWarning | Warning about suspicious syntax |
| UserWarning | Warning generated by user code |
What is an Exception?
An exception is an event that occurs during program execution, affecting the normal execution of the program.
In general, when Python cannot normally process a program, an exception will occur.
Exceptions are Python objects that represent an error.
When a Python script encounters an exception, we need to catch and handle it, otherwise the program will terminate execution.
Exception Handling
Catching exceptions can be done using try/except statements.
The try/except statement is used to detect errors in the try statement block, allowing the except statement to capture and handle exception information.
If you don't want your program to end when an exception occurs, simply capture it in the try block.
Syntax:
The following is the simple try....except...else syntax:
try:<statement> #run other code
except <name>:<statement> #if 'name' exception is raised in try part
except <name>, <data>:<statement> #if 'name' exception is raised, get additional data
else:<statement> #if no exception occurs
How try works: When starting a try statement, python marks the current context of the program, so that when an exception occurs, it can return here. The try clause executes first, what happens next depends on whether an exception occurs during execution.
- If an exception occurs when executing the statement after try, python jumps back to try and executes the first except clause that matches the exception. After exception handling is complete, control flow passes through the entire try statement (unless a new exception is raised while handling the exception).
- If an exception occurs in the statement after try, but there is no matching except clause, the exception will be passed to the upper try, or to the top level of the program (this will end the program and print the default error message).
- If no exception occurs when executing the try clause, python will execute the statement after the else statement (if there is an else), then control flow passes through the entire try statement.
Example
The following is a simple example that opens a file, writes content to the file, and no exception occurs:
Example
#!/usr/bin/python
# -*- coding: UTF-8 -*-
try:
fh = open("testfile", "w")
fh.write("This is a test file, used to test exceptions!!")
except IOError:
print "Error: File not found or read file failed"
else:
print "Content written to file successfully"
fh.close()
The above program output:
$ python test.py
Content written to file successfully
$ cat testfile # View the written content
This is a test file, used to test exceptions!!
Example
The following is a simple example that opens a file, writes content to the file, but the file does not have write permissions, causing an exception:
Example
#!/usr/bin/python
# -*- coding: UTF-8 -*-
try:
fh = open("testfile", "w")
fh.write("This is a test file, used to test exceptions!!")
except IOError:
print "Error: File not found or read file failed"
else:
print "Content written to file successfully"
fh.close()
Before executing the code for testing convenience, we can first remove the write permission of the testfile file with the following command:
chmod -w testfile
Then execute the above code:
$ python test.py
Error: File not found or read file failed
Using except without any exception type
You can use except without any exception type, as shown in the following example:
try:
Normal operations
......................
except:
Execute this code block when exception occurs
......................
else:
Execute this code block if no exception occurs
The above approach, the try-except statement catches all occurring exceptions. However, this is not a good way, as we cannot identify specific exception information through this program. Because it captures all exceptions.
Using except with multiple exception types
You can also use the same except statement to handle multiple exception information, as shown below:
try:
Normal operations
......................
except(Exception1[, Exception2[,...ExceptionN]]):
Execute this code block if one of the above multiple exceptions occurs
......................
else:
Execute this code block if no exception occurs
try-finally Statement
The try-finally statement will execute the final code regardless of whether an exception occurs.
try:<statement>
finally:<statement> #always executed when exiting try
raise
Example
Example
#!/usr/bin/python
# -*- coding: UTF-8 -*-
try:
fh = open("testfile", "w")
fh.write("This is a test file, used to test exceptions!!")
finally:
print("Error: File not found or read file failed")
If the opened file does not have write permissions, the output is as follows:
$ python test.py
Error: File not found or read file failed
The same example can also be written in the following way:
Example
#!/usr/bin/python
# -*- coding: UTF-8 -*-
try:
fh = open("testfile", "w")
try:
fh.write("This is a test file, used to test exceptions!!")
finally:
print("Close file")
fh.close()
except IOError:
print("Error: File not found or read file failed")
When an exception is thrown in the try block, the finally block code is executed immediately.
After all statements in the finally block are executed, the exception is triggered again and the except block code is executed.
The content of arguments is different from the exception.
Exception Arguments
An exception can carry arguments, which can serve as parameters for outputting exception information.
You can capture exception arguments through the except statement, as shown below:
try:
Normal operations
......................
except ExceptionType, Argument:
You can output the value of Argument here...
The values received by variables usually contain the exception statement. In tuple form, variables can receive one or more values.
Tuples usually contain error strings, error numbers, and error locations.
Example
The following is an example of a single exception:
Example
#!/usr/bin/python
# -*- coding: UTF-8 -*-
# Define function
def temp_convert(var):
try:
return int(var)
except ValueError, Argument:
print "Parameter does not contain number\n", Argument
# Call function
temp_convert("xyz")
The above program execution result is as follows:
$ python test.py
Parameter does not contain number
invalid literal for int() with base 10: 'xyz'
Triggering Exceptions
We can use the raise statement to trigger our own exceptions
The raise syntax format is as follows:
raise [Exception [, args [, traceback]]]
In the statement, Exception is the exception type (for example, NameError), args is the exception parameter provided by yourself.
The last parameter is optional (rarely used in practice), if it exists, it is the traceback exception object.
Example
An exception can be a string, class, or object. Most of Python's core-provided exceptions are instantiated classes, which are instances of a class parameter.
Defining an exception is very simple, as shown below:
Example
def functionName( level ):
if level < 1:
raise Exception("Invalid level!", level)
# After triggering exception, subsequent code will not be executed
Note: To be able to catch exceptions, the "except" statement must have the same exception to throw class objects or strings.
For example, to catch the above exception, the "except" statement is as follows:
try:
Normal logic
except Exception,err:
Trigger custom exception
else:
Other code
Example
Example
#!/usr/bin/python
# -*- coding: UTF-8 -*-
# Define function
def mye( level ):
if level < 1:
raise Exception, "Invalid level!"
# After triggering exception, subsequent code will not be executed
try:
mye(0)# Trigger exception
except Exception,err:
print 1, err
else:
print 2
Executing the above code, the output result is:
$ python test.py
1 Invalid level!
User-defined Exceptions
By creating a new exception class, programs can name their own exceptions. Exceptions should typically inherit from the Exception class, directly or indirectly.
The following is an example related to RuntimeError. In the example, a class is created with RuntimeError as the base class, used to output more information when an exception is triggered.
In the try statement block, after the user-defined exception is executed, the except block statement is executed, and variable e is used to create an instance of the Networkerror class.
class Networkerror(RuntimeError):
def __init__(self, arg):
self.args = arg
After defining the above class, you can trigger the exception as follows:
try:
raise Networkerror("Bad hostname")
except
YouTip