Python-exception encoding details

Source: Internet
Author: User

Python-exception encoding details
Exception Code details
This time we will learn the details behind try, raise, assert, and with statements. As we can see, although these statements are mostly simple, they provide powerful tools to handle exceptions in Python code.

========================================================== ========================================================== =

Try/retry t/else statement
Try is a composite statement. Its most complete form is as follows. The first line is try, followed by the Indented statement code, followed by one or more limit t clauses to identify exceptions to be captured, and finally an optional else clause. Keywords such as try, begin T, and else are indented to the same level.

try:    
 
  except 
  
   :    
   
    except 
    
     :    
     
      except 
      
        as 
       : 
        
         except: 
         
          else: 
          
         
        
      
     
    
   
  
 
In this statement, the code block under the first line of try represents the main action of this statement: the code of the program to be executed. The explain T clause defines the processor of exceptions thrown in the try code block, while the else clause (if written) provides the processor to be executed without exceptions. When the try code block is executed, the limit t clause captures any exceptions that occur when the try code block is executed. The else clause is executed only when the try code block is executed without exceptions.

 

========================================================== ========================================================== =
Try clause
When writing a try statement, some clauses can appear after the try statement code block. The following table lists all possible forms:

 

Sentence format Description
Except t: Catch all (other) exception types
Counter t name: Only capture specific exceptions
Counter t name, value: Capture the listed exceptions and their extra data (or instances)
T (name1, name2 ): Catch any listed exceptions
Struct T (name1, name2), value: Capture any listed exceptions and obtain additional data
Else: If no exception is thrown, run
Finally: This code block will always run, whether or not exceptions occur
[1]. When the Exception name (except T :) is not listed in the clause, all exceptions not listed in the try statement are caught.
[2]. When T clause uses brackets to list a group of exceptions [when T (e1, e2, e3):] will capture any listed exceptions.

Python checks the except T clause from the beginning to the end and finds whether there is a conformity in a try. Therefore, the brace version is like every exception column in its except T clause, but the statement body only needs to be compiled once. The following is an example of multiple processing t clauses, demonstrating the processor's Specificity:

try:    action()except NameError:    ...except IndexError:    ...except KeyError:    ...except (AttributeError,TypeError,SyntaxError):    ...else:    ...
Python will view the limit t clause from start to end and left to right, and then execute the first statement that matches the limit T. If the statement does not match, the exception will be passed outside the try.
If you want to write a common "capture everything" clause, you can do it with an empty limit T.
try:    action()except NameError:    ...except IndexError:    ...except:    ...else:    ...
An empty limit t clause is a common function: because it captures anything and can make the processor generic or specific. Sometimes, this form is more convenient. For example, the following is an example of capturing everything, but not listing any events.
try:    action()except:    ...
However, the empty compaction T may cause some design problems: Despite convenience, it may also capture unexpected system exceptions unrelated to the program code, and may accidentally intercept exceptions from other processors, for example, in Python, an exception is triggered even if the system leaves the call. Python3 introduces an alternative to solving one of these problems-capturing an Exception named Exception has almost the same effect as an empty consumer T, but ignores exceptions related to system exit.
try:    action()except Exception:    ...
Certificate --------------------------------------------------------------------------------------------------------------------------------------
Example: Use try/finally to write termination Behavior
The following is a more practical example, demonstrating the typical role of a finally clause.
class MyError(Exception):    passdef stuff(file):    raise MyError()file  = open('data','w')try:    stuff(file)finally:    file.close()print('not reached')
In this Code, the try with a finally Clause encapsulates the call of a file processing function to ensure that the file is always closed no matter whether the function is abnormal or not. In this way, the code later determines that the content in the output cache of the file has been transferred from the memory to the disk. Similar code structure can ensure that the server connection is closed.
========================================================== ========================================================== =====
Unified try/try t/finally statements
In all Python versions earlier than Python2.5, the try statement has two forms, both of which are independent statements: We can use the finally clause to ensure that the Code is cleared and executed, you can also write the parse T code block to capture and recover specific exceptions and define the else clause. That is, the finally clause cannot be mixed with limit T and else.
However, in Python2.5 and later versions, the two statements have been merged. Now you can mix finally, distinct T, and else clauses in the same try statement. That is, you can write the following statements:
try:    main-actionexcept Exception1:    handler1except Exception2:    handler2...else:    else-blockfinally:    finally-block
When a try statement is combined like this, the try statement must have a break t or a finally statement, and its partial order must be as follows:
Try-> sort T-> else-> finally
Among them, else and finally are optional, and there may be 0 or more t, but if one else appears, there must be at least one t.
Certificate --------------------------------------------------------------------------------------------------------------------------------------

 

Example of merging try
The following code describes four common scenarios and uses print statements to describe their meanings:

sep = '-'*32+'\n'print(sep+'exception raised and caught')try:    x = 'spam'[99]except IndexError:    print('except run')finally:    print('finally run')print('after run')print(sep + 'no exception raised')try:    x = 'spam'[3]except IndexError:    print('except run')finally:    print('finally run')print('after run')print(sep +'no exception raised,with else')try:    x = 'spam'[3]except IndexError:    print('except run')else:    print('else run')finally:    print('finally run')print('after run')print(sep +'exception raised but not caught')try:    x = 1/0except IndexError:    print('except run')finally:    print('finally run')print('after run')
The running result is as follows:
--------------------------------exception raised and caughtexcept runfinally runafter run--------------------------------no exception raisedfinally runafter run--------------------------------no exception raised,with elseelse runfinally runafter run--------------------------------exception raised but not caughtfinally runTraceback (most recent call last):  File "F:/data/PythonTest/2_25.py", line 47, in 
 
      x = 1/0ZeroDivisionError: division by zero
 
========================================================== ========================================================== =====
Raise statement
You can use the raise statement to display the trigger exception. The raise statement is composed of the raise keyword, followed by an optional instance of the class or class to be triggered:

 

 

raise 
 
  raise 
  
 
In Python3, exceptions are always class instances. Therefore, the first raise format is the most common here. An instance is provided directly or created before raise, it is either included in the raise statement. If we pass a class, Python calls a class without constructor parameters to create an instance. This format is equivalent to adding parentheses after class references.

See some examples. For built-in exceptions, the following two forms are equivalent, which will trigger an instance of the specified exception class. However, the first method is to create an instance implicitly.
raise IndexErrorraise IndexError()
We can also create an instance in advance-because the raise statement accepts any type of object reference, the following two examples can also cause IndexError:
exc = IndexError()raise excexcs = [IndexError,TypeError]raise excs[0]
If a try contains a clause named alias t name as X:, the variable X is allocated to the instance in the request:
try:    ...except IndexError as X:    ...
As is optional in the try processor, but it will allow the processor to access data in the instance and methods in the exception class. The following example defines a user-defined exception and uses the as Keyword:
>>> try:raise MyExc('Gavin')except MyExc as X:print(X.args)('Gavin',)
========================================================== ========================================================== =====
Assert statement
Python also includes assert statements, which can be considered conditional raise statements. The statement format is:
assert 
 
  ,
  
 
The execution is like the following code:
if __debug__:    if not 
 
  :        raise AssertionError(
  )
 
That is, if the test calculation is false, Python will cause an exception. assertionError is a built-in exception, and the _ debug _ flag is a built-in variable name. Unless the-0 flag is used, it is automatically set to 1 (true value ).

Assert statements are generally used to verify the program status during development and collect user-defined constraints, rather than capturing internal program design errors. It should be that Python will collect program design errors on its own. As follows:
def reciprocal(x):    assert x != 0    return 1/x
This type of assert is generally redundant: Because Python will automatically cause exceptions when an error occurs, so that Python can do a good job for you.
========================================================== ========================================================== =====

 

With/as Environment Manager

Python3 introduces a new exception-related statement: with and its optional as statements. This statement is designed to work with the Environment manager object. The with/as statement designer is an alternative to common try/finally usage modes. Like try/finally statements, with/as statements are also used to define the necessary termination or "cleanup actions", regardless of whether an exception occurs in the processing step.

The basic format of the with statement is as follows:

 

with expression [as variable]:    with-block
The expression here returns an object to support the environment management protocol. If the selected as clause exists, this object can also return a value and assign a value to the variable name variable.
Some built-in Python objects have been reinforced and support the environment management protocol. Therefore, they can be used for with statements. For example, if the file object has an Environment Manager, the file can be automatically closed after the with code block, whether or not an exception is thrown.

 

 

with open(r'C:\test\data') as myfile:    for line in myfile:        print(line)        ...
Here, the call to open will return a simple file object and assign it to the variable name myfile. We can use a general file tool to use myfile.
After the with statement is executed, the environment management mechanism ensures that the object referenced by myfile is automatically closed, even if an exception occurs during the for loop when the file is processed. However, we cannot easily know when this will happen. This use of the with statement is an alternative, allowing us to determine that a specific code block will be closed after execution. However, we can also use a more general and clear try/finally statement to implement similar functions. However, this requires four lines of Management Code instead of one line:
myfile = open(r'C:\test\data')try:    for line in myfile:        print(line)        ...finally:    myfile.close()
In addition to file objects, the lock and Conditional Variable synchronization objects defined by the multi-thread module can also be used with the with statement because they support the environment management protocol. We will introduce it later.
Certificate -----------------------------------------------------------------------------------------------------------------------------------
The Environment Management Protocol is not described here.

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.