Python Exception Handling Summary

Source: Internet
Author: User
Tags integer division syslog
Recently, to do a small project often encounter python anomalies, people are very headache, so the exception to the collation, to avoid the next encounter abnormal at a loss, the following is the collation of Python exception.

1.Python Exception Class

Abnormal Describe
Nameerror Try to access a variable that is not declared
Zerodivisionerror Divisor is 0
SyntaxError Syntax error
Indexerror Index out of sequence range
Keyerror Request a dictionary keyword that does not exist
IOError Input/output error (e.g. the file you want to read does not exist)
Attributeerror Attempting to access an unknown object property
ValueError The parameter type passed to the function is incorrect, such as passing in a character to the Int () function

2. Catching exceptions

Python's complete catch exception statement is a bit like this:

Try:try_suiteexcept exception1,exception2,..., argument:exception_suite ... #other exception blockelse:no_ Exceptions_detected_suitefinally:always_execute_suite

The amount ... Isn't it complicated? Of course, when we want to catch an exception, we don't have to write it down exactly as we did in the format above, we can discard the else statement, or the finally statement, or even exception the statement, and keep the finally statement. Uh, dizzy? All right, here we go, one by one instructions.

2.1 Try...except ... Statement

Try_suite I say everyone knows that it is the code that we need to catch the exception. And the except statement is the key, we try to capture the code snippet Try_suite in the exception, will be handed to except to handle.

The simplest form of the try...except statement is as follows:

Try:try_suiteexcept:exception Block

The above except clause does not follow any exception and exception parameters, so whatever the try catches any exception will be given to the exception block of the EXCEPT clause for processing. What if we were going to deal with a particular exception, for example, if we just wanted to deal with the exception of 0, and if the other exception appeared, let it be thrown out of the process? At this point, we're going to pass the exception parameter to the EXCEPT clause! That Exceptionn is the exception class that we're going to give the except clause (refer to the Exception Class table), which indicates that if such an exception is caught, it is given to this except clause to handle. Like what:

As an example:

>>> Try:  ... res = 2/0 ... Except Zerodivisionerror:  ... Print "Error:divisor must not being zero!" ... Error:divisor must not being zero!

Look, we really caught the zerodivisionerror anomaly! What if I want to catch and handle multiple exceptions? There are two ways to pass in multiple exception class arguments to a except clause, the other is to write multiple except clauses, each passing in the exception class parameter you want to handle. Even these two usages can be mixed up! Let me give you an example.

Try:floatnum = float (raw_input ("Please input a float:")) intnum = Int (floatnum) print 100/intnumexcept zerodivisionerror: Print "error:you must input a float num which is large or equal then 1!" Except Valueerror:print "error:you must input a float num!" [Root@cherish tmp]# python test.py Please input a float:fjiaError:you must input a float num! [Root@cherish tmp]# python test.py Please input a float:0.9999error:you must input a float num which is large or equal the N 1! [Root@cherish tmp]# python test.py please input a float:25.0914

The example above is understood by everyone and no longer explained. As long as you understand, our except can handle an exception, multiple exceptions, and even all exceptions.

You may have noticed, we haven't explained what the argument is after the except clause. Don't worry, listen to my one by one-way. This argument is actually an instance of an exception class (Don't tell me you don't know what an instance is), and it contains diagnostic information from the exception code. In other words, if you catch an exception, you can get more information about the exception by using an instance of the exception class. For example:

>>> Try:  ... 1/0 ... Except Zerodivisionerror,reason:  ... Pass ... >>> type (reason)
 
  
   
  >>> Print Reasoninteger division or modulo by zero>>> Reasonzerodivisionerror (' integer division or modulo by Zero ',) >>> reason.__class__
  
   
    
   >> > reason.__class__.__doc__ ' Second argument to a division or modulo operation is zero. ' >>> reason.__class__.__name__ ' zerodivisionerror '
  
   
 
  

In the example above, we have captured 0 exceptions, but nothing has been done. That reason is an example of an exception class Zerodivisionerror, as can be seen through type.

2.2 Try except ... else statement

Now let's talk about the else statement. There are many special else usages in python, such as for conditions and loops. In a try statement, it does the same thing: The Else statement is executed when no exception is detected. For example, you may be more aware of the following:

>>> Import syslog>>> try:  ... f = open ("/root/test.py") ... except ioerror,e:  ... Syslog.syslog (syslog. Log_err, "%s"%e) ... else:  ... Syslog.syslog (syslog. Log_info, "no exception caught\n") ... >>> f.close ()

2.3 Finally statement

The finally clause is a piece of code that executes regardless of whether an exception is detected. We can discard the except clause and the ELSE clause, use try...finally alone, or use it with except.

For example, 2.2, if there are other exceptions, cannot be caught, the program exits unexpectedly, then the file F is not properly closed. This is not the result we would like to see, but if we put the F.close statement in the finally statement, whether or not there is an exception, the file will be closed gracefully, wouldn't it be wonderful

Copy Code

>>> Import syslog>>> try:  ... f = open ("/root/test.py") ... except ioerror,e:  ... Syslog.syslog (syslog. Log_err, "%s"%e) ... else:  ... Syslog.syslog (syslog. Log_info, "no exception caught\n") ... finally: >>>  f.close ()

3. Two special methods for handling exceptions

3.1 Assertion (Assert)

What is assertion, first look at syntax:

Assert Expression[,reason]

Where assert is the keyword of the assertion. When the statement is executed, the expression is judged first, and if the expression is true, nothing is done and an exception is thrown if the expression is not true. Reason is the same as the instance of the exception class we talked about earlier. Don't understand? That's okay, give me an example! The most real!

>>> assert Len (' love ') = = Len (' like ') >>> assert 1==1>>> assert 1==2, "1 are not equal 2!" Traceback (most recent call last): File "
 
  
   
  ", line 1, in assertionerror:1 are not 
  
   
    
   equal 2!
  
   
 
  

We can see that if the expression after the assert is true, then nothing is done, and if it is not true, the Assertionerro exception is thrown, and the string we pass in will exist as the concrete information of the instance of the exception class. In fact, an assert exception can also be captured by a try block:

>>> Try:   ... Assert 1 = = 2, "1 is not equal 2!" ... except Assertionerror,reason:   ... Print "%s:%s"% (Reason.__class__.__name__,reason) ... Assertionerror:1 is not equal 2!>>> type (reason)
 
  

3.2. Context management (with statement)

If you use the Try,except,finally code only to ensure that the shared resources (such as files, data) are only assigned and released after the task is over, you are blessed! This with statement allows you to free yourself from the try,except,finally! The syntax is as follows:

With context_expr [as Var]:
With_suite

Don't you understand? It's normal, for instance!

>>> with open ('/root/test.py ') as f: ...   For line in F: ...     

What did these lines of code do?

(1) Open file/root/test.py

(2) Assigning a file object to F

(3) Output all rows of the file

(4) Python will close this file for us regardless of the exception in the code, and we don't need to be concerned with these details.

Now, do you understand that using the WITH statement to use these shared resources, we don't have to worry about not releasing him for some reason. But not all objects can use the With statement, only objects that support the context management protocol are allowed, and which objects support the protocol? As the following table

File

Decimal. Contex

Thread. LockType

Threading. Lock

Threading. Rlock

Threading. Condition

Threading. Semaphore

Threading. Boundedsemaphore

As for what is the context management protocol, if you are not only concerned with how to use with, and which objects can use with, then we are not much more concerned with this problem

4. Throwing Exceptions (Raise)

What if we want to actively throw an exception in our own program? Raise statements can help us achieve our goals. The basic syntax is as follows:

raise [Someexception [, Args [, Traceback]]
The first argument, someexception must be an exception class, or an instance of an exception class

The second parameter is the argument passed to Someexception, which must be a tuple. This parameter is used to pass useful information about the exception.

The third parameter, Traceback, is rarely used, mainly to provide a follow-up record pair (Traceback)
Let's take a few examples:

>>> Raise Nameerrortraceback (most recent): File "
 
  
   ", line 1, in 
   
    nameerror>>> raise Nameerror () #异常类的实例Traceback (most recent call last): File" 
    
      ", line 1, in 
     
      nameerror>>> raise Nameerror, (" There was a name error "," in Test.py ") Traceback (Mo St recent Call last): File " 
      
       ", line 1, in 
       
        >>> raise Nameerror ("There is a name ER Ror "," in Test.py ") #注意跟上面一个例子的区别Traceback (most recent call last): File" 
        
         ", line 1, in 
         
           Nameerror: (' There is a name ' error ', ' in test.py ') >>> raise Nameerror,nameerror ("There was a name error", "in test.py ") #注意跟上面一个例子的区别Traceback (most recent call last): File" 
          
           ", line 1, in 
           
             Nameerror: (' There is a name "error ', ' in test.py ')
            
           
          
         
        
       
   
       
 
    
    

  
 

In fact, our most commonly used is that only the first parameter is used to indicate the exception type, and at most one tuple is passed in to give the explanatory information. As a third example above.

5. Exception and SYS modules

Another way to get exception information is through the Exc_info () function in the SYS module. The function returns a ternary group: (Exception class, instance of exception class, followed by Record object)

>>> Try:   ... 1/0 ... Except:   ... Import Sys ...   tuple = Sys.exc_info () ... >>> print tuple (
 
  
   
  , zerodivisionerror (' integer division or modulo by zero ' ,), 
  
   
    
   ) >>> for i in tuple: ...   Print I 
   ... 
    
     
     #异常类    integer division or modulo by zero #异常类的实例
    
     
      
      #跟踪记录对象
    
     
   
    
  
   
 
  

Thank you for reading, hope to help everyone, thank you for the support of this site!

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