Python Exception Handling
Python provides two very important features for handling exceptions and errors that occur during the running of a Python program. You can use these features to debug Python programs.
- Exception handling: covered in detail in this Python tutorial.
- Assertions: covered in detail in this Python tutorial.
Python standard exceptions
| Exception name | Description |
|---|---|
| BaseException | Base class for all exceptions |
| SystemExit | Interpreter requests to exit |
| KeyboardInterrupt | User interrupts execution (usually by entering ^C) |
| Exception | Base class for general errors |
| StopIteration | Iterator has no more values |
| GeneratorExit | A generator raises an exception to signal exit |
| StandardError | Base class for all built-in standard exceptions |
| ArithmeticError | Base class for all numeric computation errors |
| FloatingPointError | Floating-point calculation error |
| OverflowError | Numeric operation exceeds the maximum limit |
| ZeroDivisionError | Division (or modulo) by zero (all data types) |
| AssertionError | Assertion statement failed |
| AttributeError | Object has no such attribute |
| EOFError | No built-in input, reached the EOF marker |
| EnvironmentError | Base class for operating system errors |
| IOError | Input/output operation failed |
| OSError | Operating system error |
| WindowsError | System call failed |
| ImportError | Failed to import module/object |
| LookupError | Base class for invalid data queries |
| IndexError | Index not in sequence |
| KeyError | Key not in mapping |
| MemoryError | Out of memory error (not fatal for the Python interpreter) |
| NameError | Undeclared/uninitialized object (no attributes) |
| UnboundLocalError | Access to an uninitialized local variable |
| ReferenceError | A weak reference attempts to access an object that has already been garbage collected |
| RuntimeError | General runtime error |
| NotImplementedError | Method not yet implemented |
| SyntaxError | Python syntax error |
| IndentationError | Indentation error |
| TabError | Mixing tabs and spaces |
| SystemError | General interpreter system error |
| TypeError | Invalid operation for the type |
| ValueError | Invalid argument passed |
| UnicodeError | Unicode-related error |
| UnicodeDecodeError | Error during Unicode decoding |
| UnicodeEncodeError | Error during Unicode encoding |
| UnicodeTranslateError | Error during Unicode conversion |
| Warning | Base class for warnings |
| DeprecationWarning | Warning about deprecated features |
| FutureWarning | Warning about constructs whose semantics will change in the future |
| OverflowWarning | Warning about automatic promotion to long integer (long) |
| 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 the execution of a program and disrupts its normal flow.
Generally, an exception occurs when Python cannot handle a program properly.
An exception is a Python object that represents an error.
When an exception occurs in a Python script, we need to catch and handle it, otherwise the program will terminate.
Exception handling
Exceptions can be caught using try/except statements.
The try/except statement is used to detect errors in a try block, allowing the except statement to catch and handle the exception information.
If you do not want your program to end when an exception occurs, simply catch it in the try block.
Syntax:
The following is a simpletry....except...elsesyntax:
try:
<语句> #运行别的代码
except <名字>:
<语句> #如果在try部份引发了'name'异常
except <名字>,<数据>:
<语句> #如果引发了'name'异常,获得附加的数据
else:
<语句> #如果没有异常发生
The way try works is that after a try statement begins, Python marks the current context of the program so that it can return here when an exception occurs. The try clause is executed first, and what happens next depends on whether an exception occurs during execution.
- If an exception occurs while executing the statements after try, Python jumps back to try and executes the first except clause that matches the exception. After the exception is handled, control flow passes through the entire try statement (unless a new exception is raised while handling the exception).
- If an exception occurs in the statements after try but there is no matching except clause, the exception is passed to an outer try, or to the top level of the program (which will end the program and print the default error message).
- If no exception occurs during the execution of the try clause, Python executes the statements after the else clause (if there is an else), and then control flow passes through the entire try statement.
Example
The following is a simple example that opens a file, writes content into it, and no exception occurs:
Example
#!/usr/bin/python
-- coding: UTF-8 --
try
:
fh
=
open
(
"testfile"
,
"w"
)
fh.
write
(
"This is a test file for testing exceptions!!"
)
except
IOError
:
"Error: file not found or failed to read file"
else
:
"Content written to file successfully"
fh.
close
(
)
The output of the above program:
$ python test.py
内容写入文件成功
$ cat testfile # 查看写入的内容
这是一个测试文件,用于测试异常!!
Example
The following is a simple example that opens a file and writes content into it, but the file has no write permission, so an exception occurs:
Example
#!/usr/bin/python
-- coding: UTF-8 --
try
:
fh
=
open
(
"testfile"
,
"w"
)
fh.
write
(
"This is a test file for testing exceptions!!"
)
except
IOError
:
"Error: file not found or failed to read file"
else
:
"Content written to file successfully"
fh.
close
(
)
For testing convenience before executing the code, 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: 没有找到文件或读取文件失败
Using except without any exception type
You can use except without any exception type, as in the following example:
try: normal operation ...................... except: if an exception occurs, execute this block of code ...................... else: if no exception occurs, execute this block of code
The above try-except statement catches all exceptions that occur. But this is not a good approach, because we cannot identify the specific exception information through the program, as it catches all exceptions.
Using except with multiple exception types
You can also use the same except statement to handle multiple exception messages, as shown below:
try:
正常的操作
......................
except(Exception1[, Exception2[,...ExceptionN]]):
发生以上多个异常中的一个,执行这块代码
......................
else:
如果没有异常执行这块代码
The try-finally statement
The try-finally statement executes the final code whether or not an exception occurs.
try:
<语句>
finally:
<语句> #退出try时总会执行
raise
Example
Example
#!/usr/bin/python
-- coding: UTF-8 --
try
:
fh
=
open
(
"testfile"
,
"w"
)
fh.
write
(
"This is a test file for testing exceptions!!"
)
finally
:
"Error: file not found or failed to read file"
If the opened file has no write permission, the output is as follows:
$ python test.py
Error: 没有找到文件或读取文件失败
The same example can also be written as follows:
Example
#!/usr/bin/python
-- coding: UTF-8 --
try
:
fh
=
open
(
"testfile"
,
"w"
)
try
:
fh.
write
(
"This is a test file for testing exceptions!!"
)
finally
:
"Close the file"
fh.
close
(
)
except
IOError
:
"Error: file not found or failed to read file"
When an exception is raised in a try block, the finally block code is executed immediately.
After all statements in the finally block are executed, the exception is raised again and the except block code is executed.
The content of the argument differs from the exception.
Exception arguments
An exception can carry arguments, which can serve as output exception information parameters.
You can catch the arguments of an exception through the except statement, as shown below:
try:
正常的操作
......................
except ExceptionType, Argument:
你可以在这输出 Argument 的值...
The exception value received by a variable is usually contained in the statement of the exception. In tuple form, a variable can receive one or more values.
A tuple usually contains an error string, an error number, and an error location.
Example
The following is an example of a single exception:
Example
#!/usr/bin/python
-- coding: UTF-8 --
Defining a function
def
temp_convert
(
var
)
:
try
:
return
int
(
var
)
except
ValueError
,
Argument:
"The argument does not contain a number\n"
,
Argument
Calling a function
temp_convert
(
"xyz"
)
The result of running the above program is as follows:
$ python test.py
参数没有包含数字
invalid literal for int() with base 10: 'xyz'
Raising exceptions
We can raise exceptions ourselves using the raise statement
The raise syntax is as follows:
raise [Exception [, args [, traceback]]]
In the statement, Exception is the type of exception (for example, NameError), an argument is any of the standard exceptions, and args are the exception arguments provided by yourself.
The last parameter is optional (rarely used in practice); if present, it is a traceback exception object.
Example
An exception can be a string, a class, or an object. Most exceptions provided by the Python core are instantiated classes, with arguments that are instances of a class.
Defining an exception is very simple, as shown below:
Example
def
functionName
(
level
)
:
if
level
<
1
:
raise
Exception
(
"Invalid level!"
,
level
)
After an exception is raised, the code that follows will not be executed
**Note:** In order to catch an exception, the "except" statement must throw a class object or string with the same exception.
For example, to catch the above exception, the "except" statement is as follows:
try:
正常逻辑
except Exception,err:
触发自定义异常
else:
其余代码
Example
Example
#!/usr/bin/python
-- coding: UTF-8 --
Defining a function
def
mye
(
level
)
:
if
level
<
1
:
raise
Exception
,
"Invalid level!"
After an exception is raised, the code that follows will not be executed
try
:
mye
(
0
)
Raising exceptions
except
Exception
,
err:
1
,
err
else
:
2
The output of the code above is:
$ python test.py
1 Invalid level!
User-defined exceptions
By creating a new exception class, a program can name its own exceptions. Exceptions should typically inherit from the Exception class, either directly or indirectly.
The following is an example related to RuntimeError, in which a class with RuntimeError as its base class is created to output more information when an exception is raised.
In the try block, after the user-defined exception, the except block statement is executed, and the variable e is used to create an instance of the Networkerror class.
class Networkerror(RuntimeError):
def __init__(self, arg):
self.args = arg
After you define the above class, you can raise the exception as follows:
try:
raise Networkerror("Bad hostname")
except Networkerror,e:
print e.args