Python Exception Handling

Python provides two very important features to handle exceptions and errors that occur during the running of Python programs. You can use these features to debug Python programs.

  • Exception Handling: This site's Python tutorial will cover it in detail.
  • Assertions: This site's Python tutorial will cover it in detail.

Python Standard Exceptions

Exception NameDescription
BaseExceptionBase class for all exceptions
SystemExitInterpreter requested exit
KeyboardInterruptUser interruption of execution (usually by entering ^C)
ExceptionBase class for general errors
StopIteration Iterator has no more values
GeneratorExit Generator raises an exception to notify exit
StandardErrorBase class for all built-in standard exceptions
ArithmeticError Base class for all numeric calculation errors
FloatingPointError Floating point calculation error
OverflowErrorNumeric operation exceeds maximum limit
ZeroDivisionErrorDivision (or modulo) by zero (all data types)
AssertionErrorAssertion statement failed
AttributeErrorObject 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
WindowsErrorSystem call failed
ImportError Import module/object failed
LookupError Base class for invalid data queries
IndexErrorNo such index in sequence
KeyErrorNo such key in mapping
MemoryErrorMemory overflow error (not fatal for the Python interpreter)
NameErrorUndeclared/uninitialized object (no attributes)
UnboundLocalError Accessing an uninitialized local variable
ReferenceErrorWeak reference attempts to access an object that has been garbage collected
RuntimeError General runtime error
NotImplementedErrorMethod not yet implemented
SyntaxErrorPython syntax error
IndentationErrorIndentation error
TabErrorMixing tabs and spaces
SystemError General interpreter system error
TypeErrorInvalid operation on type
ValueError Invalid argument passed
UnicodeError Unicode-related errors
UnicodeDecodeError Error during Unicode decoding
UnicodeEncodeError Error during Unicode encoding
UnicodeTranslateErrorError during Unicode conversion
Warning Base class for warnings
DeprecationWarningWarning about deprecated features
FutureWarning Warning about constructs whose semantics will change in the future
OverflowWarningOld warning about automatic promotion to long integer (long)
PendingDeprecationWarningWarning about features that will be deprecated
RuntimeWarning Warning about suspicious runtime behavior
SyntaxWarningWarning about suspicious syntax
UserWarningWarning generated by user code

What is an exception?

An exception is an event that occurs during program execution and affects the normal execution of the program.

In general, when Python cannot process a program normally, an exception occurs.

Exceptions are Python objects that represent an error.

When an exception occurs in a Python script, we need to catch and handle it, otherwise the program will terminate.


Exception Handling

You can catch exceptions using try/except statements.

The try/except statement is used to detect errors in the try block, so that the except statement can catch exception information and handle it.

If you don't want your program to end when an exception occurs, just catch it in a try.

Syntax:

The following is the simpletry....except...elsesyntax:

try:
<语句>        #运行别的代码
except <名字>:
<语句>        #如果在try部份引发了'name'异常
except <名字>,<数据>:
<语句>        #如果引发了'name'异常,获得附加的数据
else:
<语句>        #如果没有异常发生

The way try works is that when a try statement is started, Python makes a mark in the context of the current 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 when the statement after try executes, Python jumps back to try and executes the first except clause that matches the exception. After the exception is handled, the 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 submitted to the upper-level 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 will execute the statement after the else statement (if there is an else), then the control flow passes through the entire try statement.

Example

The following is a simple example that opens a file, writes content to 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:
    print "Error: File not found or failed to read file"
else:
    print "Content written to file successfully"
    fh.close()

The above program output is:

$ python test.py 
内容写入文件成功
$ cat testfile       # 查看写入的内容
这是一个测试文件,用于测试异常!!

Example

The following is a simple example that opens a file, writes content to it, but the file does not have 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:
    print "Error: File not found or failed to read file"
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. The command is as follows:

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:
    正常的操作
   ......................
except:
    发生异常,执行这块代码
   ......................
else:
    如果没有异常执行这块代码

This way the 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:
    如果没有异常执行这块代码

try-finally Statement

The try-finally statement executes the final code regardless of whether 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:
    print "Error: File not found or failed to read file"

If the opened file does not have write permission, the output is as follows:

$ python test.py 
Error: 没有找到文件或读取文件失败

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 for testing exceptions!!")
    finally:
        print "Close file"
        fh.close()
except IOError:
    print "Error: File not found or failed to read file"

When an exception is thrown in the try block, the code in the finally block 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 parameter is different from the exception.


Exception Arguments

An exception can carry arguments, which can be used as parameters for output exception information.

You can catch the arguments of an exception via the except statement, as shown below:

try:
    正常的操作
   ......................
except ExceptionType, Argument:
    你可以在这输出 Argument 的值...

The exception value received by the variable is usually contained in the exception statement. The variable can receive one or more values in the form of a tuple.

The tuple usually contains the error string, error number, and error location.

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 "Argument does not contain a number"\n", Argument

# Call function
temp_convert("xyz")

The above program execution result is as follows:

$ python test.py 
参数没有包含数字
invalid literal for int() with base 10: 'xyz'

Raising Exceptions

We can use the raise statement to raise an exception ourselves

The syntax of raise is as follows:

raise [Exception [, args [, traceback]]]

In the statement, Exception is the type of the exception (e.g., NameError), one of the standard exceptions; args is the exception argument you provide yourself.

The last parameter is optional (rarely used in practice); if present, it is the traceback object.

Example

An exception can be a string, a class, or an object. Most exceptions provided by the Python core are instantiated classes, which are parameters of a class instance.

Defining an exception is very simple, as shown below:

Example

def functionName( level ):
    if level < 1:
        raise Exception("Invalid level!", level)
        # After the exception is raised, the subsequent code will not be executed

Note:In order to catch an exception, the "except" statement must use the same exception class object or string that was raised.

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 -*-

# Define a function
def mye( level ):
    if level < 1:
        raise Exception,"Invalid level!"
        # After the exception is raised, the subsequent code will not be executed
try:
    mye(0)            # Raise the exception
except Exception,err:
    print 1,err
else:
    print 2

Executing the above code, the output 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, either directly or indirectly.

The following is an example related to RuntimeError. In the example, a class is created with the base class RuntimeError, used to output more information when the exception is triggered.

In the try block, the except block executes after the user-defined exception is raised. The 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 raise the exception as follows:

try:
    raise Networkerror("Bad hostname")
except Networkerror,e:
    print e.args
Other Extensions