Python exception handling


Python provides two very important functions to handle exceptions and errors that occur when python programs are running. You can use this feature to debug python programs.

  • Exception handling: This site’s Python tutorial will introduce it in detail.

  • Assertions: This site’s Python tutorial will introduce them in detail.


python standard exception

Exception name Description


BaseException Base class for all exceptions
SystemExit Interpreter request to exit
KeyboardInterrupt User interrupts execution (usually by entering ^C)
Exception Base class for general errors
StopIteration Iterator has no more values
GeneratorExit Generator Notify exit when an exception occurs
StandardError The 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 the maximum limit
ZeroDivisionError Division (or modulo) zero (all data types)
AssertionError Assertion statement failed
AttributeError The object does not have this attribute
EOFError No built-in input, EOF flag reached
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 Invalid data query base Class
IndexError The index does not exist in the sequence
KeyError Not found in the mapping This key
MemoryError Memory overflow error (not fatal to the Python interpreter)
NameError Undeclared/initialized object (no properties)
UnboundLocalError Accessing uninitialized local variable
ReferenceError Weak reference attempts to access an object that has been garbage collected
RuntimeError General runtime error
NotImplementedError Not yet implemented method
SyntaxError Python syntax error
IndentationError Indentation error
TabError Mixed tabs and spaces
SystemError General interpreter system errors
TypeError Invalid operation on type
ValueError Passing in invalid parameters
UnicodeError Unicode related errors
UnicodeDecodeError Unicode decoding Error
UnicodeEncodeError Unicode encoding error
UnicodeTranslateError Unicode conversion error
Warning Base class for warnings
DeprecationWarning Warning about deprecated features
FutureWarning Warning about construction semantics that will change in the future
OverflowWarning Old about automatic Warning for promotion to long
PendingDeprecationWarning Warning about feature being deprecated
RuntimeWarning Suspicious runtime behavior warning
SyntaxWarning Suspicious syntax warning
UserWarning Warning 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.

Generally, an exception occurs when Python cannot handle the program normally.

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 execution.


Exception handling

To catch exceptions, you can use the try/except statement.

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

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

Grammar:

The following is the syntax of a simpletry....except...else:

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

The working principle of try is, After starting a try statement, Python marks the context of the current program so that you 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 is executed, python will jump back to try and execute the first except clause that matches the exception. After the exception is handled, the control flow passes The entire try statement (unless a new exception is thrown when 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 try, or to the top level of the program (this will end program and print the default error message).

  • If no exception occurs when the try clause is executed, Python will execute the statement after the else statement (if there is an else), and then the control flow passes through the entire try statement.

Example

The following is a simple example, it opens a file, writes the content in the file, and no exception occurs:

#!/usr/bin/python # -*- coding: UTF-8 -*- try: fh = open("testfile", "w") fh.write("这是一个测试文件,用于测试异常!!") except IOError: print "Error: 没有找到文件或读取文件失败" else: print "内容写入文件成功" fh.close()

Output results of the above program:

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

Example

The following is a simple example. It opens a file and writes the content in the file, but the file does not have write permission. An exception occurred:

#!/usr/bin/python # -*- coding: UTF-8 -*- try: fh = open("testfile", "w") fh.write("这是一个测试文件,用于测试异常!!") except IOError: print "Error: 没有找到文件或读取文件失败" else: print "内容写入文件成功" fh.close()

For the convenience of testing before executing the code, 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: 没有找到文件或读取文件失败

Use except without any exception type

You can use except without any exception type, as shown in the following example:

try: 正常的操作 ...................... except: 发生异常,执行这块代码 ...................... else: 如果没有异常执行这块代码

The above method try-except statement captures all occurrences exception. But this is not a good way, we cannot identify specific abnormal information through this program. Because it catches all exceptions.


Use 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 will execute the last code regardless of whether an exception occurs.

try: <语句> finally: <语句> #退出try时总会执行 raise

Example

#!/usr/bin/python # -*- coding: UTF-8 -*- try: fh = open("testfile", "w") fh.write("这是一个测试文件,用于测试异常!!") finally: print "Error: 没有找到文件或读取文件失败"

If the opened file does not have writable permissions, the output will be as follows:

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

The same example can also be written as follows:

#!/usr/bin/python # -*- coding: UTF-8 -*- try: fh = open("testfile", "w") try: fh.write("这是一个测试文件,用于测试异常!!") finally: print "关闭文件" fh.close() except IOError: print "Error: 没有找到文件或读取文件失败"

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 the parameter is different from the exception.


Exception parameters

An exception can take parameters, which can be used as output exception information parameters.

You can capture exception parameters through the except statement, as follows:

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

The exception value received by the variable is usually included in the exception statement. Variables in the form of tuples 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:

#!/usr/bin/python # -*- coding: UTF-8 -*- # 定义函数 def temp_convert(var): try: return int(var) except ValueError, Argument: print "参数没有包含数字\n", Argument # 调用函数 temp_convert("xyz");

The execution results of the above program are as follows:

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

Trigger exception

We can use the raise statement to trigger exceptions ourselves

The syntax format of raise is as follows:

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

Exception in the statement is the type of exception (for example, NameError) and the parameter is an exception parameter value. This parameter is optional, if not provided, the exception parameter is "None".

The last parameter is optional (rarely used in practice) and, if present, is the trace exception object.

Example

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

Defining an exception is very simple, as follows:

def functionName( level ): if level < 1: raise Exception("Invalid level!", level) # 触发异常后,后面的代码就不会再执行

Note:In order to be able to catch the exception, the "except" statement must use the same exception to throw the class object or string.

For example, if we catch the above exception, the "except" statement is as follows:

try: 正常逻辑 except "Invalid level!": 触发自定义异常 else: 其余代码

Example

#!/usr/bin/python # -*- coding: UTF-8 -*- # 定义函数 def mye( level ): if level < 1: raise Exception("Invalid level!", level) # 触发异常后,后面的代码就不会再执行 try: mye(0) // 触发异常 except "Invalid level!": print 1 else: print 2

Execute the above code, the output result is:

$ python test.py Traceback (most recent call last): File "test.py", line 11, in  mye(0) File "test.py", line 7, in mye raise Exception("Invalid level!", level) Exception: ('Invalid level!', 0)

User-Defined Exceptions

Programs can name their own exceptions by creating a new exception class. Exceptions should typically inherit from the Exception class, either directly or indirectly.

The following are examples related to RuntimeError. A class is created in the example. The base class is RuntimeError, which is used to output more information when an exception is triggered.

In the try statement block, the except block statement is executed after the user-defined exception. 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 trigger the exception as follows:

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