"Python" Exception handling

Source: Internet
Author: User

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 the string to the Int () function

2. Catching Exceptions

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

1 Try:2 Try_suite3 exceptexception1,exception2,..., Argument:4 Exception_suite5......#Other exception block6 Else:7 No_exceptions_detected_suite8 finally:9Always_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:

Try :    try_suiteexcept  Exception:    Exception block

As an example:

Try :...      = 2/except  zerodivisionerror     : ... Print " Error:divisor must not being zero! "   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.

1 Try:2Floatnum = Float (raw_input ("Please input a float:"))3Intnum =Int (floatnum)4     Print100/Intnum5 exceptZerodivisionerror:6     Print "error:you must input a float num which is large or equal then 1!"7 exceptValueError:8     Print "error:you must input a float num!"9 Ten[[email protected] tmp]#python test.py One Please input a Float:fjia A error:you must input a float num! -[[email protected] tmp]#python test.py -Please input a float:0.9999 theError:you must input a float num which isLargeorEqual then 1! -[[email protected] tmp]#python test.py -Please input a float:25.091 -4

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 ...exceptZerodivisionerror,reason: ...Pass... >>>type (reason)<type'exceptions. Zerodivisionerror'>>>>PrintReasoninteger Divisionormodulo by Zero>>>Reasonzerodivisionerror ('integer division or modulo by zero',)>>> reason.__class__<type'exceptions. Zerodivisionerror'>>>> 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

>>>Importsyslog>>>Try: ... f= Open ("/root/test.py")... exceptioerror,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 exceptions3.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!

>>>assertLen' Love') = = Len (' like')>>>assert1==1>>>assert1==2,"1 is not equal 2!"Traceback (most recent): File"<stdin>", Line 1,inch<module>Assertionerror:1 is  notEqual 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:...     assert1 = = 2,"1 is not equal 2!"... exceptAssertionerror,reason: ...Print "%s:%s"% (reason.__class__.__name__, Reason) ... Assertionerror:1 is  notEqual 2!>>>type (reason)<type'exceptions. Assertionerror'>

3.2. Context management (with statement)

"Python" Exception handling

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.