Python exception handling summary, python exception handling
Recently, a small project often encounters Python exceptions, which can be a headache. Therefore, we need to organize 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 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)<type 'exceptions.ZeroDivisionError'>>>> print reasoninteger division or modulo 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 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?
Copy code
>>> 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 "<stdin>", line 1, in <module>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)<type 'exceptions.AssertionError'>
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 "<stdin>", line 1, in <module> NameError >>> raise NameError () # exception class instance 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 ") # note the difference between 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 ") # note the difference between Traceback (most recent call last): File" <stdin> ", line 1, in <module> 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... failed T :... 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'> # exception class integer division or modulo by zero # instance of the exception class <traceback object at 0x7f538a318b48> # tracking record object
Thank you for reading this article. I hope it will help you. Thank you for your support for this site!