Python Error and exception summary _python

Source: Internet
Author: User
Tags assert integer division stdin syslog throw exception in python
In advance, this is not an article about a full description of Python anomalies, it's just a note-and-summary article after learning the python exception. What the? You don't know what an anomaly is, uh ...

1.Python Exception class

Python is an object-oriented language, so exceptions thrown by programs are also classes. There are a few common python exceptions, as long as you have a rough glance, an image, and when you're programmed, believe that you'll be sure to face them more than once (unless you're not using Python).

Abnormal Describe
Nameerror Attempt to access a variable that is not declared
Zerodivisionerror Divisor is 0
SyntaxError Syntax error
Indexerror Index exceeded sequence range
Keyerror Request a dictionary keyword that does not exist
IOError Input and output error (for example, the file you want to read does not exist)
Attributeerror Attempted to access an unknown object property
ValueError Incorrect parameter type passed to function, such as passing string shape to int () function

2. Catch exceptions

Python's complete capture of exceptions is a bit like this:

Copy Code code as follows:

Try
Try_suite
Except Exception1,exception2,..., Argument:
Exception_suite
... #other exception block
Else
No_exceptions_detected_suite
Finally
Always_execute_suite

Amount of ... Is it complicated? Of course, when we're going to catch an exception, we don't have to write it all down in the format above, we can throw out the else statement, or finally statement, and not even exception the statement, leaving the finally statement. Uh, dizzy? All right, here we go. One by one notes.

2.1.try...except ... Statement

Try_suite I say as we all know, is that we need to catch the exception code. The except statement is the key, and when we try to capture the exception in the code snippet Try_suite, we'll give it to except.

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

Copy Code code as follows:

Try
Try_suite
Except
Exception block

The EXCEPT clause above does not follow any exception and exception parameters, so any exception that is caught by a try is handled by the exception block of the EXCEPT clause. What if we want to deal with a particular exception, for example, if we just want to deal with 0 exceptions, and if the other exception appears, let it be thrown out of the process? This time, we will give the EXCEPT clause passed the exception parameter! That Exceptionn is the exception class that we want to give the except clause (refer to the Exception Class table), which means that if this type of exception is caught, it is handled by the EXCEPT clause. Like what:

Copy Code code as follows:

Try
Try_suite
Except Exception:
Exception block

As an example:

Copy Code code as follows:

>>> Try:
... res = 2/0
... except Zerodivisionerror:
... print "error:divisor must not to be zero!"
...
Error:divisor must not to be zero!

Look, we really caught a zerodivisionerror anomaly! What if I want to capture and handle multiple exceptions? There are two ways to pass a except clause to multiple exception class parameters, the other is to write multiple except clauses, and each clause is passed into the exception class parameter that you want to handle. Even, these two uses can mix! Let me give you an example.

Copy Code code as follows:

Try
Floatnum = float (raw_input ("Please input a float:"))
intnum = Int (floatnum)
Print 100/intnum
Except 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:fjia
Error:you must input a float num!
[Root@cherish tmp]# python test.py
Please input a float:0.9999
Error:you must input a float num which is large or equal then 1!
[Root@cherish tmp]# python test.py
Please input a float:25.091
4

The above example is understood by all, and it is no longer explained. As long as you understand, our except can handle an exception, a variety of exceptions, and even all the anomalies.

As you may have noticed, we haven't explained what the argument behind the EXCEPT clause is. Don't worry, listen to me in one by one ways. This argument is actually an instance of an exception class (Don't tell me you don't know what an instance is) that 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:

Copy Code code as follows:

>>> Try:
... 1/0
... except Zerodivisionerror,reason:
. Pass
...
>>> type (reason)
<type ' exceptions. Zerodivisionerror ' >
>>> Print Reason
Integer division or modulo by zero
>>> Reason
Zerodivisionerror (' 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 '

For the example above, we've captured 0 exceptions, but we didn't do anything. That reason is an instance of the exception class Zerodivisionerror, as can be seen by type.

2.2try. Except...else statement
Now let's talk about this else statement. Python has a number of special else usages, such as for conditions and loops. In a try statement, it works the same way: When an exception is not detected, the Else statement is executed. For example, you might know better:

Copy Code code as follows:

>>> 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 clause
The finally clause is a piece of code that executes regardless of whether an exception is detected. We can discard except clause and ELSE clause, use try...finally alone, also can cooperate with except etc. use.

For example 2.2, if there are other exceptions that cannot be captured and the program exits abnormally, then file F is not shut down properly. This is not what we would like to see, but if we put the F.close statement in the finally statement, whether or not there is an exception, will normally close the file, it is not very good

Copy Code code as follows:

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

You see, we have the above example to use the try,except,else,finally these four clauses! :-), isn't it funny? By now, you've basically learned how to catch a normal exception and handle it in Python.

3. Two special procedures for handling anomalies

3.1 Assertion (Assert)
What is an assertion, first look at the grammar:

Copy Code code as follows:

Assert Expression[,reason]

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

Copy Code code as follows:

>>> assert Len (' love ') = = Len (' like ')
>>> assert 1==1
>>> assert 1==2, "1 is not equal 2!"
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
Assertionerror:1 is not equal 2!

We can see that if the expression behind the assert is true, nothing is done, and if it is not true, the Assertionerro exception is thrown, and the string we pass in is the exact information of the instance of the exception class. In fact, an assert exception can also be caught by a try block:

Copy Code code as follows:

>>> 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)
<type ' exceptions. Assertionerror ' >

3.2. Context management (with statement)
If you use try,except,finally code just to make sure that your shared resources (such as files, data) are only allocated and released after the task is over, then you are blessed! This with statement allows you to liberate yourself from the try,except,finally! The syntax is as follows:

Copy Code code as follows:

With context_expr [as Var]:
With_suite

Do you not understand? Very normal, for instance!

Copy Code code as follows:

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

What do these lines of code do?
(1) Open file/root/test.py
(2) Assigning a file object to F
(3) Output all lines of the file
(4) Regardless of the exception in the code, Python will close the file for us, we do not need to care about these details.
Now, is it clear 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 (Contextual Management Protocol), which objects support the protocol? As shown in the following table:
File

Decimal. Context
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 too concerned about the problem:

4. Throw exception (Raise)

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

Copy Code code as follows:

raise [Someexception [, Args [, Traceback]]

First argument, someexception must be an exception class, or an instance of an exception class
The second parameter is the argument passed to the someexception, which must be a tuple. This parameter is used to pass useful information about this exception.
The third parameter traceback is rarely used, mainly to provide a Record object (Traceback)
Let's give a few examples here.

Copy Code code as follows:

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

In fact, our most common use is to just pass in the first parameter to indicate the type of exception, and then pass in a tuple to give the descriptive information. As the third example above.

5. Exceptions 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, following Record object)

Copy Code code as follows:

>>> Try:
... 1/0
... except:
. Import Sys
... tuple = Sys.exc_info ()
...
>>> Print Tuple
(<type ' exceptions.) Zerodivisionerror ' ", Zerodivisionerror (' integer division or modulo by zero"), <traceback object at 0X7F538A318B48 >)
>>> for i in tuple:
... print I
...
<type ' exceptions. Zerodivisionerror ' > #异常类
Integer division or modulo by zero #异常类的实例
<traceback object at 0x7f538a318b48> #跟踪记录对象

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.