Python Errors and Exceptions summary

Source: Internet
Author: User
Tags integer division syslog
This is not an exhaustive article about Python exceptions, just a note-taking and summary-Nature article after learning about Python anomalies. What the? You still don't know what the anomaly is, the amount ...

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 wait until the program is programmed, I'm sure you'll see them more than once (unless you don't use Python).

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:

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

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:

Copy the Code code as follows:


Try
Try_suite
Except
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:

Copy the Code code as follows:


Try
Try_suite
Except Exception:
Exception block

As an example:

Copy the Code code as follows:


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

Copy the 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 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:

Copy the Code code as follows:


>>> Try:
... 1/0
... except Zerodivisionerror,reason:
... pass
...
>>> type (reason)

>>> Print Reason
Integer division or modulo by zero
>>> Reason
Zerodivisionerror (' 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.2try ... 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:

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

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

3. Two special methods for handling exceptions

3.1 Assertion (Assert)
What is assertion, first look at syntax:

Copy the Code code as follows:


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!

Copy the Code code as follows:


>>> assert Len (' love ') = = Len (' like ')
>>> assert 1==1
>>> assert 1==2, "1 is not equal 2!"
Traceback (most recent):
File " ", line 1, in
Assertionerror:1 is 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:

Copy the 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)

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:

Copy the Code code as follows:


With context_expr [as Var]:
With_suite

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

Copy the Code code as follows:


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

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. 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 much more concerned about this issue:)

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:

Copy the Code code 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 seldom used, mainly to provide a follow-up record object (Traceback)
Let's give a few examples.

Copy the Code code as follows:


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

Actually, the only thing we use most often is passing in the first parameter to indicate the type of exception, A maximum of one tuple is passed in to give the explanatory information. As a third example above.

5. Exception and SYS module

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)

Copy code code as follows:


>>> try:
... 1/0
... except:
... import sys
... tuple = Sys.exc_info ()
...
>>> Print tuple
( )
>>> for i in tuple:
... print i
...
#异常类
Integer division or modulo by zero #异常类的实例
Traceback object at 0x7f538a318b48> #跟踪记录对象
  • 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.