Latest web development tutorials

Python exception handling

python provides two very important functions to handle exceptions and errors python program that appears in the operation. You can use this feature to debug python programs.

  • Exception handling: Python tutorial site specific description.
  • Assert (Assertions): Python tutorial site specific description.

python standard exceptions

The exception name description
BaseException The base class for all exceptions
SystemExit Interpreter request to exit
KeyboardInterrupt User Interrupt Executing (usually enter ^ C)
Exception General error base class
StopIteration Iterator no more values
GeneratorExit Generator (generator) to notify the abnormal exit
StandardError All of the built-in standard base class for exceptions
ArithmeticError All numerical error base class
FloatingPointError Floating-point calculation error
OverflowError Numerical operations exceeded the maximum limit
ZeroDivisionError In addition to (or modulus) zero (all data types)
AssertionError Assertion failure
AttributeError This object has no property
EOFError No built-in input and arriving EOF marker
EnvironmentError Operating system error base class
IOError Input / output operations to fail
OSError Operating system error
WindowsError System call failed
ImportError Import Module / object failed
LookupError Invalid class data base queries
IndexError Without this sequence index (index)
KeyError Without this key mapping
MemoryError Memory overflow error (for Python interpreter is not fatal)
NameError Undeclared / initialize the object (not property)
UnboundLocalError Access uninitialized local variable
ReferenceError Weak reference objects (Weak reference) have been trying to access the garbage collection of
RuntimeError General runtime error
NotImplementedError The method has not been implemented
SyntaxError Python syntax error
IndentationError Indent error
TabError Tab and space mix
SystemError Usually interpreter system error
TypeError Invalid operation type
ValueError Invalid arguments passed in
UnicodeError Unicode related errors
UnicodeDecodeError Unicode decoding of error
UnicodeEncodeError Unicode code error
UnicodeTranslateError Unicode conversion error
Warning Warning base class
DeprecationWarning Warnings about deprecated features
FutureWarning Warnings about the future structure of the semantics have changed
OverflowWarning The old warning about automatically promoted to a long integer (long) of
PendingDeprecationWarning It will be a warning about waste characteristics
RuntimeWarning Suspicious runtime behavior (runtime behavior) warning
SyntaxWarning Syntax warnings suspicious
UserWarning Warns the user code generation

What is abnormal?

That exception is an event that will occur during the execution of the program, affecting the normal program execution.

Under normal circumstances, when Python programs do not properly handle an exception occurs.

Exception is Python object representing an error.

An exception occurs when the Python script we need to capture handle it, otherwise the program will be terminated.


Exception Handling

You can catch the exception using try / except statement.

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

If you do not want an exception occurs when the end of your program, just try to catch it in the inside.

grammar:

The following is a simple try .... except ... else syntax:

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

try works, when starting a try statement is, python will be marked in the context of the current program, so that when an abnormality occurs can be back here, try clause is executed first, what happens next depends on execution whether there is an exception.

  • If an exception occurs when you try to perform when the statement after, python jump back to try and perform the first matching except clause is the exception, exception processing is completed, the control flow on through the entire try statement (unless an exception is processed time and trigger a new exceptions).
  • If an abnormality occurs in the try statement after the years, but no matching except clause, an exception will be submitted to the top of the try, or to the top of the program (which will end the program, and print a default error message).
  • If an exception occurs when you try clause is not executed, python else statement will be executed after the statement (if then else), then the flow of control through the entire try statement.

Examples

Here is a simple example, it opens a file, the contents of the file content is written, and is not an exception occurs:

#!/usr/bin/python
# -*- coding: UTF-8 -*-

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

The above program output:

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

Examples

Here is a simple example, it opens a file, the contents written in the file contents, 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()

Before executing the code in order to facilitate the testing, we can first remove write access to the file testfile command is as follows:

chmod -w testfile

Then execute the code above:

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

Except without using any type of exception with

You can use without any exception type except, the following examples:

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

Above manner try-except statement to catch all exceptions that occur. But this is not a good way, through this program we can not identify the specific exception information. Because it captures all the exceptions.


And with the use of multiple types of exceptions except

You can also use the same except statements to handle multiple exceptions, as follows:

try:
    正常的操作
   ......................
except(Exception1[, Exception2[,...ExceptionN]]]):
   发生以上多个异常中的一个,执行这块代码
   ......................
else:
    如果没有异常执行这块代码

try-finally statement

try-finally statement, whether an exception occurs will perform the final code.

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

Examples

#!/usr/bin/python
# -*- coding: UTF-8 -*-

try:
    fh = open("testfile", "w")
    fh.write("这是一个测试文件,用于测试异常!!")
finally:
    print "Error: 没有找到文件或读取文件失败"

If you open a file does not have write permission, output is 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 thrown an exception in the try block, the finally block of code immediately.

finally block all statements after the execution, the exception is triggered again and execution except block code.

Contents of the parameter is different from the exception.


Abnormal parameters

An exception can take parameters, as abnormality information output parameters.

You can catch the exception through parameter statements except as follows:

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

Outlier variables typically included in the received exception statement. Variables in the form of tuples may receive one or more values.

Tuple typically contains the error string, wrong number, wrong location.

Examples

The following are examples 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");

Results of the above procedures are as follows:

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

Trigger abnormal

We can use the statement to raise themselves trigger an exception

raise syntax is as follows:

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

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

The last argument is optional (rarely used in practice), if there is a trace exception object.

Examples

An exception can be a string, a class or object. Python's exception provided by the kernel, most are instances of the class, which is a parameter of an instance of a class.

Very simple definition of an exception, as follows:

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

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

For example, we capture more than an exception, "except" statement is as follows:

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

Examples

#!/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

Implementation of the above code, the output is:

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

User-defined exceptions

By creating a new exception class, the program may name their own exceptions. Typical exceptions should be inherited from the Exception class, either directly or indirectly.

Following is associated with RuntimeError instance instance create a class, the base class is RuntimeError, for outputting additional information when an exception is triggered.

In the try block, the user performs a block statement except custom exception, variable e is used to create instances Networkerror class.

class Networkerror(RuntimeError):
    def __init__(self, arg):
        self.args = arg

After you define the above categories, you can trigger the exception, as follows:

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