Exception handling for Python

Source: Internet
Author: User
Tags assert throw exception

In all programs, you will encounter exceptions, some of which are generated when code is written, and may cause the program to fail to run directly during the early stages. This class of exceptions, when writing code, the program can directly troubleshoot the changes. However, some exceptions are generated during the course of the program's operation, possibly because the data obtained by the user interaction is not recognized, or because the failure of the network request causes the program to continue and so on. In order to prevent the program from crashing, this kind of error requires the programmer to consider and handle the corresponding exception in writing. Each language has its own corresponding exception defense mechanism, Python in particular, not only to the wrong debug statements, but also provides a huge built-in exception class, so that we can precisely for different exceptions to give different processing methods. For specific exception classification information in Python, you can refer to the official documentation, the address is as follows: (in the official document, built-in exceptions include warnings and exception levels, it is recommended to look together)

Chinese Address: http://python.usyiyi.cn/translate/python_352/library/exceptions.html#concrete-exceptions

English Address: Https://docs.python.org/3/library/exceptions.html#concrete-exceptions

After knowing the specific classification of the exception, it is necessary to discuss the prediction of the occurrence of anomalies, what should be done, Python's exception defense is relatively simple, commonly used only three statements, and in debugging without all use. Let's look at a simple debug statement:

Try:    print (name) #打印变量name的值except Exception: #如果有异常则输出告警 Exception can catch any exception in Python, which belongs to the exception base class    print ("Error!") "" " The output results are as follows/library/frameworks/python.framework/versions/3.5/bin/python3.5/users/penglong/documents/python/s10/day4 /exception handling. Pyerror! Process finished with exit code 0 "" "

The code, as shown above, is a simple exception handler, and the code module is try-except. The code content of the try is the business module, followed by the except need to catch the exception type, the above code in order to demonstrate, the direct use of the base class, in practical use we often need to catch the specific exception class, and then give a specific processing method, specifically for the next code to explain. The code for the except subordinate is the processing module after catching the exception. After a brief demonstration of an exception handling, here is a slightly more complex exception handling, with a reference to two additional statements about exception handling

namlist = [' test1 ', ' test2 '] #定义一个数组, length 2try:print (namlist[3]) # The code block in try to print namlist[3] is obviously subscript out of bounds except Nameerror as error: #尝试捕获NameError and assigns its print information to the error 
#NameError的具体定义参见官方文档. Print ("Nameerror:", error) #在except的代码块 prints the captured exception information except Indexerror as error: #在尝试捕获上一个异常之后, try to catch another exception directly. Print ("Indexerror:", error) except Exception as Error: #再次尝试 print ("Exception:", error) Else: #else语句, The usage here is followed by the exception. If the exception that we predicted is not captured, the code module that executes the statement
#在本段代码中, which is not possible because the exception exception class was attempted to be captured. Just a description of how to use print ("If you don't catch one, I'll be good for you") finally: #finally语句, at the end of the exception defense, you can skip the else direct use. Whether or not an exception is caught, his subordinate code snippet executes print ("I'm there," no matter what you catch or not, "" ") the output is as follows/library/frameworks/python.framework/versions/3.5/bin/ python3.5/users/penglong/documents/python/s10/day4/exception handling. Pyindexerror:list index out of range whether you catch it or not, I'm here. Process Finished with exit code 0

From the output information above we can see that we have captured a indexerror, and the program finally executed the finally code module. This is basically python's usual exception handling. In addition to an uncontrolled exception, some code requires specific operating conditions, so we can assume that an exception is thrown. There are two ways to throw exceptions in Python, assertions, or raise statements. Where the assertion needs to determine the condition, and raise is the type of exception that needs to be thrown directly after it. The two applications are slightly different in my understanding, and assertions are often used to determine whether to throw an exception based on conditions. For example, the initial value of a variable is empty, the program runs to half it gets the data from the network, and if there is no data, the program cannot execute. You can use assertions to determine if a variable is empty, throw an exception directly if it is empty, and give an alarm. Of course, raise can do the same thing, but it requires an if discriminant. Thus, in terms of code usage, assertions are more concise and can be captured by exception. Let's look at the assertion mechanism first:

NUM1 = 1 #定义俩变量num2 = 1 "" "assertion keyword is used, followed by a decision condition, and no exception if the condition is true. Not tenable, throw exception. 
with "," split, followed by the alarm information. Alarm information can also be omitted "" "assert num1 + num2 = = 3," The brain is a good thing, I hope you have a. " Good calculation! "Print (" yes ")" "" Output result/library/frameworks/python.framework/versions/3.5/bin/python3.5/users/penglong/ documents/python/s10/day4/exception handling. Pytraceback (most recent): File "/users/penglong/documents/python/s10/day4/ Exception handling. py ", line x, in <module> assert num1 + num2 = = 3," The brain is a good thing, I hope you have one. Good calculation! " Assertionerror: The brain is a good thing, I hope you have one. Good calculation! Process finished with exit code 1 "" "
# # # # # #断言异常捕获测试 ####### #num1 = 1num2 = 1try:assert Num1 + num2 = 3," The brain is a good thing, I hope You have a. Good calculation! " Except Assertionerror as Error:print (error) "" "Output result/library/frameworks/python.framework/versions/3.5/bin/python3.5 /users/penglong/documents/python/s10/day4/exception handling. Py The brain is a good thing, I hope you have one. Good calculation! Process finished with exit code 0 "" "#可以看到打印信息为我们定义的告警信息

As above, the code gives the condition is obviously not tenable, so the program output an exception. In terms of use, the assertion statement is used for known conditional debugging relative brevity. The above code exception belongs to the calculation error, and the alarm information is custom. But some exceptions when Python defines the exception class inside, in order to facilitate fast, we can directly throw, do not need to define the exception information, then need to raise to solve. The simple code is as follows:

Raise Nameerror ("Name error!") #抛出一个NameError异常, you can give a print message, or you can not give the # General custom specific exception information should try to throw exception class here only to do other class demonstrations. Print ("But there is no error!") #抛出异常后尝试打印点神马 "" "Output result/library/frameworks/python.framework/versions/3.5/bin/python3.5/users/penglong/documents/ python/s10/day4/exception handling. Pytraceback (most recent):  File "/users/penglong/documents/python/s10/day4/ Exception handling. Py ", line up, in <module>    raise Nameerrornameerror:name error! #如果没给参数, there is no specific error message process finished with Exit code 1 "" "

As above, raise can directly throw Python's own exception class, a look to know where the error, so if you do not need the condition to determine the custom exception information, try to throw exception class. This does not confuse the exception information. The above code is based on the function demonstration, in the actual use, once throws the exception, the program will crash. So general throw exceptions are mostly used for code debugging. If it is to prevent unknown information, throw an exception should appear the Try--except statement of the try subordinate code module, and then use except capture, and then give the corresponding solution.

The above is Python's common exception handling mechanism, Python's exception class is numerous, basically can satisfy the daily need. For the exception article, most of the custom exceptions are discussed, but I have not yet encountered the need to customize the exception, often simple custom alarm information and other requirements can be directly changed with the built-in. Of course, many test scenarios do require more accurate exception information, so you may need to recreate an exception class module yourself, which is not discussed in this article. It is worth mentioning that many modules can be found in the Python Open source forum, if you really need to find out first.

Exception handling for Python

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.