Python exception handling summary

Source: Internet
Author: User
This article mainly introduces python exception-related information and sorts out relevant exception information. if you need it, you can refer to it recently. a small project may encounter Python exceptions, which is a headache, therefore, sort out exceptions to avoid confusion next time. The following describes how to organize Python exceptions.

1. Python exception class

Exception Description
NameError Try to access a variable without declaration
ZeroDivisionError The 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 (for example, the file you want to read does not exist)
AttributeError Attempt to access unknown object properties
ValueError The parameter type passed to the function is incorrect. for example, a character is input to the int () function.

2. capture exceptions

The complete exception capture statement in Python is a bit like:

try: try_suiteexcept Exception1,Exception2,...,Argument: exception_suite...... #other exception blockelse: no_exceptions_detected_suitefinally: always_execute_suite

Isn't it complicated? Of course, when we want to capture exceptions, we do not have to write them down in the above format. we can discard the else statement or finally statement, or even not the exception statement, the finally statement is retained. Amount, dizzy? Okay, let's explain it one by one.

2.1 try... statement

Try_suite is the code that we need to capture exceptions. The except t statement is the key. when we try to catch the exception in the code snippet try_suite, it will be handed over to the except t for processing.

The simplest form of try... limit T statement is as follows:

try: try_suiteexcept: exception block  

The above except T clause is not associated with any exceptions and exception parameters. therefore, no matter the try captures any exceptions, it will be handed over to the exception block of the except t clause for processing. If we want to handle a specific exception, for example, we only want to handle the division by zero exception. if other exceptions occur, let them throw and do not handle them. what should we do? At this time, we need to input exception parameters to the limit T clause! The ExceptionN is the exception class we want to assign to the T t clause (see the table of exception classes). it indicates that if such exceptions are caught, they will be handed over to the except clause for processing. For example:

try: try_suiteexcept Exception: exception block 

For example:

>>> try:...  res = 2/0... except ZeroDivisionError:...  print "Error:Divisor must not be zero!"... Error:Divisor must not be zero!

Look, we actually caught ZeroDivisionError! What if I want to capture and handle multiple exceptions? There are two methods: one is to input multiple exception-type parameters to a distinct T clause, and the other is to write multiple distinct T clauses, each clause passes in the exception class parameters you want to handle. Even the two methods can be used together! Here is 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 then 1![root@Cherish tmp]# python test.py Please input a float:25.0914

As you can see from the above examples, we will not explain it any more. As long as you understand that our pipeline T can handle one exception, multiple exceptions, or even all exceptions.

You may have noticed that we haven't explained what the Argument is behind the limit T clause? Don't worry. let me hear you here. This Argument is actually an exception-type instance (don't tell me what you don't know) that contains diagnostic information from the exception code. That is to say, if you capture an exception, you can use this exception class instance to obtain more information about the exception. For example:

>>> try:...  1/0... except ZeroDivisionError,reason:...  pass... >>> type(reason)
 
  >>> print reasoninteger pision or modulo by zero>>> reasonZeroDivisionError('integer pision or modulo by zero',)>>> reason.__class__
  
   >>> reason.__class__.__doc__'Second argument to a pision or modulo operation was zero.'>>> reason.__class__.__name__'ZeroDivisionError'
  
 

In the above example, the division by zero exception is captured, but nothing is done. The reason is an error-type ZeroDivisionError instance, which can be seen through type.

2.2 try... else t... else statement

Now let's talk about this else statement. Python has many special else usage, such as used for conditions and loops. Put it in the try statement, the role is similar: When no exception is detected, the else statement is executed. For example, you may better understand:

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

A finally clause is a piece of code that is executed no matter whether an exception is detected. We can discard the limit T clause and the else clause, use try... finally separately, or use it together with limit T.

For example, in the example of 2.2, if another exception occurs and the program exits unexpectedly, the file f is not properly closed. This is not what we want to see, but if we put the f. close statement into the finally statement, the file will be normally closed no matter whether there is an exception or not, isn't it very good?


>>> 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 simple methods for handling exceptions

3.1 assert)

What are assertions? first look at the syntax:

Assert expression [, reason]

Here, assert is the keyword of assertion. When executing this statement, first judge the expression. if the expression is true, nothing is done. if the expression is not true, an exception is thrown. Reason is the same as the exception class instance we mentioned earlier. Don't you understand? It doesn't matter. for example! The most authentic!

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

We can see that if the expression following assert is true, nothing will be done. if it is not true, an AssertionErro exception will be thrown, in addition, the passed string will exist as the instance information of the exception class. In fact, assert exceptions can also be captured by try blocks:

>>> 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 try, try T, and finally code only to ensure the unique allocation of shared resources (such as files and data) and release it after the task ends, you are blessed! This with statement can free you from try, exist T, and finally! Syntax:

With context_expr [as var]:
With_suite

Don't you understand? It's normal. here is an example!

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

What did the above lines of code do?

(1) open the file/root/test. py

(2) assign a file object to f

(3) output all rows of the file

(4) whether or not exceptions occur in the code, Python will close this file for us, so we do not need to care about these details.

Now, do you understand that using the with statement to use these shared resources doesn't have to worry about releasing them for some reason. However, not all objects can use the with statement. only objects that support the context management protocol can use the with statement. which objects support this protocol? 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 about how to use with, and which objects can use with, then we will not be too concerned about this issue.

4. throw an exception (raise)

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

Raise [SomeException [, args [, traceback]
The first parameter, SomeException must be an exception class or an instance of the exception class

The second parameter is the parameter passed to SomeException, which must be a tuples. This parameter is used to pass useful information about this exception.

The third parameter traceback is rarely used. it is mainly used to provide a trace)
Here are several examples:

>>> Raise NameErrorTraceback (most recent call last): File"
 
  
", Line 1, in
  
   
NameError >>> raise NameError () # Traceback (most recent call last) of the exception class: File"
   
    
", Line 1, in
    
     
NameError >>> raise NameError, ("There is a name error", "in test. py") Traceback (most recent call last): File"
     
      
", Line 1, in
      
        >>> Raise NameError ("There is a name error", "in test. py") # note the difference between Traceback (most recent call last) and the above example: File"
       
         ", Line 1, in
        
          NameError: ('There is a name error', 'in test. py ') >>> raise NameError, NameError ("There is a name error", "in test. py ") # note the difference between Traceback (most recent call last) and the above example: File"
         
           ", Line 1, in
          
            NameError: ('There is a name error', 'In test. py ')
          
         
        
       
      
     
    
   
  
 

In fact, the most commonly used one is to input only the first parameter to indicate the exception type, and at most one tuples to provide instructions. As in the third example above.

5. exceptions and sys module

Another way to obtain exception information is through the exc_info () function in the sys module. This function returns a triple: (exception class, exception class instance, and record object)

>>> Try:... 1/0... wait T:... import sys... tuple = sys. exc_info ()... >>> print tuple (
 
  
, ZeroDivisionError ('integer pision or modulo by 0 ',),
  
   
) >>> For I in tuple:... print I...
   
    
# Exception class integer pision or modulo by zero # exception class instance
    
     
# Tracking record object
    
   
  
 

Thank you for reading this article. I hope it will help you. thank you for your support for this site!

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.