Python object-oriented-exception

Source: Internet
Author: User
Tags assert finally block stdin python script

Error differs from exception: error
    • Syntax error: Code does not conform to interpreter or compile syntax. can be modified prior to execution
    • Logic error: Incomplete or illegal input or calculation problems. Cannot be modified at execution time
Abnormal
    • An exception is an event that occurs during program execution and affects the normal execution of the program.
    • In general, an exception occurs when Python does not handle the program properly.
    • The exception is a Python object that represents an error.
    • When a Python script exception occurs, we need to capture and process it, or the program terminates execution.

The common exception
Keyboardinterrupt user interrupt execution (usually input ^c)
Zerodivisionerror Except (or modulo) 0 (all data types)
Nameerror Object not declared/initialized (no attributes)
SyntaxError Python syntax error
Indentationerror Indentation Error
Unicodedecodeerror Error in Unicode decoding
Unicodeencodeerror Unicode encoding Error
Unicodetranslateerror Unicode Conversion Error
Syntaxwarning Warning of suspicious syntax
Exception handling catch exceptions can use the Try/except statement.

The try/except statement is used to detect errors in a try statement block, allowing the except statement to catch exception information and handle it.
If you do not want to end your program when an exception occurs, simply capture it in a try.
Grammar:

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

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

Try works by starting a try statement, and Python is tagged in the context of the current program so that when an exception occurs, it can go back here, the TRY clause executes first, and what happens next depends on whether an exception occurs at execution time.
If an exception occurs when the statement after the try is executed, Python jumps back to the try and executes the first except clause that matches the exception, and the control flow passes through the entire try statement (unless a new exception is thrown when the exception is handled).
If an exception occurs in the statement after the try, but there is no matching except clause, the exception will be submitted to the upper try, or to the top of the program (This will end the program and print the default error message).
If no exception occurs when the TRY clause executes, Python executes the statement after the Else statement (if there is else), and then the control flow passes through the entire try statement.

Example 1

Here is a simple example that opens a file where the contents of the file are written and the exception does not occur:

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

内容写入文件成功

This is a test file for testing exceptions!!

Example 2

Here is a simple example that opens a file where the contents of the file are written, but the file does not have write permission, and an exception occurs:

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

In order to test the convenience before executing the code, we can first remove the testfile file Write permission, 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 in the following example:

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

The try-except statement above captures all occurrences of the exception. But this is not a good way to identify specific exception information through the program. Because it catches all the exceptions.

Using except with multiple exception types

You can also use the same except statement to handle multiple exception information, as follows:

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

Finally, the statement below is executed regardless of whether an exception was detected.

Provides a cleanup mechanism for exception handling events for closing files or freeing system resources.

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

Executes the finally block code immediately when an exception is thrown in the try block.
After all the statements in the finally block are executed, the exception is triggered again, and the except block code is executed.

parameter of the exception

An exception can take a parameter that can be used as the output exception information parameter.
You can use the except statement to catch the parameters of the exception, as follows:

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

The exception value that the variable receives is usually contained in the exception's statement. In a tuple's form, a variable can receive one or more values.
Tuples typically contain error strings, error numbers, and error locations.

Instance

The following is an instance 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 results of the above program execution are as follows:

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

1. If the try statement does not throw an exception, execute the Else statement, and then execute the finally statement.

2. If the try statement throws an exception, execute the except statement and then execute the finally statement.

try:    expressionexcept:    expressionelse:    expressionfinally:    expression
Triggering an exception

We can use the raise statement to trigger the exception ourselves
The raise syntax format is as follows:

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

The type of exception in the statement is an exception (for example, the Nameerror) parameter is an exception parameter value. This parameter is optional and if not provided, the exception parameter is "None".
The last parameter is optional (rarely used in practice) and, if present, is the tracking exception object.
Instance

An exception can be a string, a class, or an object. The Python kernel provides exceptions, most of which are instantiated classes, which are parameters of an instance of a class.
It is very simple to define an exception as follows:

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

Note: To be able to catch exceptions, the "except" statement must have the same exception to throw the class object or string.
For example, we capture the above exception, and the "except" statement looks like this:

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

Execute the above code and 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, programs can name their own exceptions. Exceptions should be typical of inheriting from the exception class, either directly or indirectly.
The following is an example of a runtimeerror-related instance in which a class is created and the base class is RuntimeError, which is used to output more information when the exception is triggered.
In the TRY statement block, after the user-defined exception executes the EXCEPT block statement, 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
Example 1
>>> class FileError(IOError):...     pass...>>> raise FileError,'Test FileError'Traceback (most recent call last):  File "<stdin>", line 1, in <module>__main__.FileError: Test FileError>>> try:...     raise FileError,'Test FileError'... except FileError,e:...     print e...Test FileError>>>
Example 2
#encoding:utf-8'''Created on Nov 16, 2016@author: Administrator'''class CustomError(Exception):    def __init__(self,info):        Exception.__init__(self)        self.errorinfo = info            def __str__(self):        return 'custom_ioerror:%s'%self.errorinfotry:    raise CustomError('test CustomError')except CustomError,e:    print 'ErrorInfo:%s'% e#output:ErrorInfo:custom_ioerror:test CustomError
The difference between raise and assert: Raise statement

The raise statement is used to actively throw exceptions
Syntax format: Raise [Exception[,args]]
Exception: Exception class
Args: A tuple describing exception information

Assert statement

Assertion statement: Assert statement is used to detect whether an expression is true
? If False, the Asserterror error is raised;
Syntax format: assert expression [, args
Expression: Expressions
Args: Descriptive information for judging conditions]

>>> raise IOError,'file not found'Traceback (most recent call last):  File "<stdin>", line 1, in <module>IOError: file not found>>>
>>> assert 7 == 6 ,'don not equal'Traceback (most recent call last):  File "<stdin>", line 1, in <module>AssertionError: don not equal>>> assert 7 == 14/2 ,'don not equal'>>>
With statement

Grammar

with context [as var]:    with_sute
    • The WITH statement is used instead of the try-except_finally statement to make the code cleaner
    • The context returns an object
    • var is used to hold the object returned by the context, for a single return value or tuple
    • With_sute using the var variable to manipulate the object returned by the context
import ostry:    with open('1.txt') as f1:        print 'in with f1.read',f1.read()        f1.seek(-5,os.SEEK_SET)      #with 语句虽然会在发生异常后执行相关如关闭文件,释放相关系统资源的操作,但是不会对异常进行处理except ValueError,e:                 #所以在except-block中对异常进一步进行处理    print 'in with cathc ValueError',e    print 'with:',f1.closed
The WITH statement is actually context management
    • 1. Context Management Protocol: the object that supports this protocol should support the __exit__ () and __enter__ () two methods.
    • 2. Context Manager: Defines the context in which to establish the runtime when executing with statements, and is responsible for the entry and exit operations of the WITH statement block context.
    • 3. Enter the context Manager: Call management method __enter(), if you set the AS VAR statement, the Var variable accepts the _enter() method return value.
    • 4. Exit the context Manager: Call the __exit__ () method.
    • If an exception is encountered during the execution of the 5.with statement, the execution of the WITH clause is not terminated, and the exception that occurs will only deliver other statement processing

Instance:

#encoding:utf-8'''Created on Nov 16, 2016@author: Administrator'''class MyContex(object):    '''自定义上下文管理器'''    def __init__(self,name):        self.name = name    def __enter__(self):        print '__enter__'        return self    def do_self(self):        print 'do_self'        a #这里设置的一个错误    #exexc_type是错误的类型,exc_value是错误的类型信息,traceback是错误的对象信息    def __exit__(self,exc_type,exc_value,traceback):        print '__exit__'        print 'Error',exc_type,'info:',exc_value        print traceback    #错误源头    # if __name__== '__main__':#     try:#         with MyContex('test context') as f:#             print f.name#             f.do_self()    #发生异常但是会继续执行,而异常由except子句处理#     except BaseException,e:#         print 'catch error in with:',eif __name__== '__main__':    with MyContex('test context') as f:            print f.name            f.do_self()

Operation Result:

__enter__test contextdo_self__exit__Error <type 'exceptions.NameError'> info: global name 'a' is not defined<traceback object at 0x00000000026843C8>Traceback (most recent call last):  File "E:\WorkSpace\Dive into Python\_Exception\_MyContex.py", line 32, in <module>    f.do_self()  File "E:\WorkSpace\Dive into Python\_Exception\_MyContex.py", line 15, in do_self    a #这里设置的一个错误NameError: global name 'a' is not defined
With statement application scenario:

Python has improved on some built-in objects and added support for the context manager, which can be used in a with statement, such as

    • 1. File operation
    • 2. Process resources are mutually exclusive shared, such as lock
    • 3. Objects that support context
Contextlib Module

The Contextlib module provides 3 objects: Adorner ContextManager, function nested, and context manager closing.

Using these objects, you can wrap existing generator functions or objects, add support for context management protocols, and avoid writing context managers specifically to support with statements.

Adorner ContextManager

ContextManager is used to decorate the generator function, when the generator function is decorated, a context manager is returned, and the enter() and exit() methods are provided by ContextManager. and is no longer the previous iteration. A decorated generator function can produce only one value, otherwise it causes an exception to be runtimeerror; If an as clause is used, the resulting value is assigned to the target in the AS clause. Let's look at a simple example.

from contextlib import contextmanager@contextmanagerdef demo():        print '[Allocate resources]'        print 'Code before yield-statement executes in __enter__'        yield '*** contextmanager demo ***'        print 'Code after yield-statement executes in __exit__'        print '[Free resources]'with demo() as value:     print 'Assigned Value: %s' % value

Operation Result:

[Allocate resources]Code before yield-statement executes in __enter__Assigned Value: *** contextmanager demo ***Code after yield-statement executes in __exit__[Free resources]

As you can see, the statement before yield in the generator function executes in the enter() method, and the statement after yield is executed in exit(), and the value produced by yield is assigned to the values variable in the AS clause.

It is important to note that ContextManager only omits the writing of enter()/ exit(), but is not responsible for the "get" and "clean" work of the resource; "Get" operation needs to be defined before the yield statement, "clean" The operation requires that the yield statement be defined so that the WITH statement executes the enter()/ exit() method to get/release the resource, that is, the generator function needs to implement the necessary logical control, An appropriate exception is thrown when an error occurs including resource access.

function nested

Nested can organize multiple context managers together, avoiding the use of nested with statements.

#nested 语法with nested(A(), B(), C()) as (X, Y, Z):    # with-body code here#类似于:with A() as X:    with B() as Y:        with C() as Z:            # with-body code here

It is important to note that after an exception occurs, if the exit() method of a context manager returns FALSE for exception handling, the outer context manager does not monitor the exception.

Context Manager closing

The implementation of closing is as follows:

class closing(object):    # help doc here        def __init__(self, thing):                self.thing = thing        def __enter__(self):                return self.thing        def __exit__(self, *exc_info):                self.thing.close()

The context manager assigns the wrapped object to the target variable of the AS clause, while ensuring that the open object is closed when the with-body is finished executing. The object that is wrapped by the closing context manager must provide the definition of the close () method, or the Attributeerror error will be reported when executed.

class ClosingDemo(object):        def __init__(self):                self.acquire()        def acquire(self):                print 'Acquire resources.'        def free(self):                print 'Clean up any resources acquired.'        def close(self):                self.free()with closing(ClosingDemo()):        print 'Using resources'

Operation Result:

Acquire resources.Using resources Clean up any resources acquired.

The closing is intended for objects that provide close () implementations, such as network connections, database connections, and so on, and can perform the required resource "cleanup" by using the interface Close () when customizing the class.

Reference: http://www.runoob.com/python/python-exceptions.html

? Http://mp.weixin.qq.com/s/LO1yyFeUA6pR_YPyfDoSig

Python object-oriented-exception

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.