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:
Copy codeThe 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:
Copy codeThe 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 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:
Copy codeThe Code is as follows:
Try:
Try_suite
Failed t Exception:
Exception block
For example:
Copy codeThe 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.
Copy codeThe 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:
Copy codeThe Code is as follows:
>>> Try:
.... 1/0
... Reset t ZeroDivisionError, reason:
... Pass
...
>>> Type (reason)
<Type 'exceptions. zerodivisionerror'>
>>> Print reason
Integer division or modulo by zero
>>> Reason
ZeroDivisionError ('integer division or modulo by 0 ',)
>>> 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.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:
Copy codeThe 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
Copy codeThe 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:
Copy codeThe 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!
Copy codeThe 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 "<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:
Copy codeThe 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)
<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:
Copy codeThe Code is as follows:
With context_expr [as var]:
With_suite
Don't you understand? It's normal. Here is an example!
Copy codeThe 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:
Copy codeThe 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.
Copy codeThe Code is as follows:
>>> Raise NameError
Traceback (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 with the preceding example.
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 with the preceding example.
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)
Copy codeThe Code is as follows:
>>> Try:
.... 1/0
... Handle T:
... Import sys
... Tuple = sys. exc_info ()
...
>>> Print tuple
(<Type 'exceptions. zerodivisionerror'>, ZeroDivisionError ('integer division or modulo by 0',), <traceback object at 0x7f538a318b48>)
>>> For I in tuple:
... Print I
...
<Type 'exceptions. zerodivisionerror'> # exception class
Integer division or modulo by zero # exception class instance
<Traceback object at 0x7f538a318b48> # tracking record object