Python errors and exceptions

Source: Internet
Author: User
This is not a comprehensive introduction to Python exceptions. it is just a note-taking record and summary article after learning Python exceptions, this is not a comprehensive introduction to Python exceptions. it is just a note-taking record and summary article after learning Python exceptions. What? You don't know what an exception is...

1. Python exception class

Python is an object-oriented language, so exceptions thrown by programs are also classes. The following are common Python exceptions. you just need to take a general look and have an image. when programming, I believe that you will not just show them at once (unless you don't need Python ).

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, you can input a string to the int () function.

2. capture exceptions

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

The code is as follows:


Try:
Try_suite
Except t Exception1, Exception2,..., Argument:
Prediction_suite
... # Other exception block
Else:
No_exceptions_detected_suite
Finally:
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..20.t..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:

The code is as follows:


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

The code is as follows:


Try:
Try_suite
Failed T Exception:
Exception block

For example:

The code is as follows:


>>> Try:
... Res = 2/0
... Reset T 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.

The code is as follows:


Try:
Floatnum = float (raw_input ("Please input a float :"))
Intnum = int (floatnum)
Print 100/intnum
Except t ZeroDivisionError:
Print "Error: you must input a float num which is large or equal then 1! "
Failed T 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

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:

The code is as follows:


>>> Try:
.... 1/0
... Reset T ZeroDivisionError, reason:
... Pass
...
>>> Type (reason)

>>> Print reason
Integer pision or modulo by zero
>>> Reason
ZeroDivisionError ('integer pision or modulo by 0 ',)
>>> 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.2try... begin 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:

The code is as follows:


>>> Import syslog
>>> Try:
... F = open ("/root/test. py ")
... Handle T 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
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 great

The code is as follows:


>>> Import syslog
>>> Try:
... F = open ("/root/test. py ")
... Handle T IOError, e:
... Syslog. syslog (syslog. LOG_ERR, "% s" % e)
... Else:
... Syslog. syslog (syslog. LOG_INFO, "no exception caught \ n ")
... Finally:
>>> F. close ()

No, we used the try, begin T, else, and finally clauses in the above example! :-) Is it interesting? Now, you have basically learned how to capture and handle common exceptions in Python.

3. two simple methods for handling exceptions

3.1 assert)
What are assertions? first look at the syntax:

The code is as follows:


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!

The code is as follows:


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

The code is as follows:


>>> Try:
... Assert 1 = 2, "1 is not equal 2! "
... Failed t 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:

The code is as follows:


With context_expr [as var]:
With_suite

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

The code is as follows:


>>> 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? See 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 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:

The code 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 tracing record object (traceback)
Here are a few examples.

The code is as follows:


>>> Raise NameError
Traceback (most recent call last ):
File" ", Line 1, in
NameError
>>> Raise NameError () # exception class instance
Traceback (most recent call last ):
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 with the preceding example.
Traceback (most recent call last ):
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 with the preceding example.
Traceback (most recent call last ):
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)

The code is as follows:


>>> Try:
.... 1/0
... Handle 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

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.