1. Anomaly concept
Definition: during the running process of the program, some errors will inevitably occur. The error messages you may often see, such as NameError, TypeError, ValueError, etc., are exceptions.
In the process of program running, once an exception occurs, the program will be terminated immediately, and all the code after the exception will not be executed. Therefore, when an exception occurs in a Python program, we need to catch and handle the exception, otherwise the program will terminate and affect the normal execution of the program.
2. Understand exceptions
When an error is detected, the interpreter cannot continue to execute, and some error prompts will appear on the console, which is the so-called "exception".
For example, if you open a nonexistent file in r mode, an exception will be thrown, which we can see in the console.
open('test.txt', 'r')
In this case, when we write code, we are not sure whether a statement will execute correctly. At this time, we can put the code with possible problems into the exception statement.
Because the exception statement will try to execute a line or a section of code that may have errors. In case of errors, you can execute another line or a section of code that must be executable to replace the wrong code. In order to ensure that the program does not report an error, you can continue to execute the program downward.
Summary:
Exceptions occur when Python programs are running. The purpose is not to let our programs terminate directly.
Instead, Python hopes that when an exception occurs, we can write code to handle the exception.
3. Abnormal writing
(1) Grammar
try: Possible error codes except: Code executed in case of exception (processing method after error)
(2) Quick experience
Requirement: try to open the file in r mode. If the file does not exist, open it in w mode.
try: f = open('test.txt', 'r') except: f = open('test.txt', 'w')
(3) Catch specified exception
1) Grammar
try: Possible error codes except Exception type: Code executed if the exception type is caught
Note: if there is an error in the code we execute, and the error type is consistent with the exception type specified in exception, the code defined under the matched exception type will be executed.
Summary:
- If exception is not followed by any content, it will catch all exceptions at this time.
- If exception is followed by an exception type, it will only catch the exception of that type at this time.
2) Experience
""" Requirement: try to print num,Catch exception type NameError, If this exception type is caught, print: your variable is not defined """ # Result: your variable is not defined try: print(num) except NameError: print('Your variable is not defined')
be careful:
- If the exception type of the code you are trying to execute is inconsistent with the exception type you are trying to catch, you cannot catch an exception.
- Generally, there is only one line of code to try to execute below try.
3) Multiple specified exceptions were caught.
Sometimes when we write code, we are not sure which exception type a line of code may throw, so we may write several more exception types.
When capturing multiple exceptions, you can put the name of the exception type to be captured after exception and write it in tuple.
try: print(1/0) except (NameError, ZeroDivisionError): print('There are errors')
As long as the exception code trying to execute, the thrown exception type matches any exception type defined in the tuple after exception, it can be caught.
Exception types of different types can also be written separately, as follows:
try: print(10/0) except NameError: print('appear NameError abnormal') except ZeroDivisionError: print('appear ZeroDivisionError abnormal') except IndexError: print('appear IndexError abnormal')
4) What is the exception type and what is the exception description information.
In the exception information viewed on the console, such as NameError: name 'num' is not defined,
NameError before the colon shows the exception type.
After the colon name 'num' is not defined, the exception description information is displayed.
5) Capture exception description information.
try: print(num) except (NameError, ZeroDivisionError) as result: print(result) # perhaps try: print(10/0) except NameError as e: print('Exception type',e) except ZeroDivisionError as e: print('Exception type',e) except IndexError as e: print('Exception type',e)
As is a keyword. The variable after the as keyword is the description information of the caught exception, and the variable name can be customized.
6) Catch all exceptions.
Exception is the parent class of all program exception classes, so if exception is followed by exception, all exceptions will be caught.
# 1. Catch all exceptions try: print(num) except Exception: print("Exception caught") # Or do not write an Exception try: print(num) except: print("Exception caught") # 2. Capture all exception information try: print(num) except Exception as result: print(result)
(4) else in exception
else represents the code to execute if there are no exceptions.
try: print(1) except Exception as result: print(result) else: print('I am else,It is the code executed when there is no exception')
(5) finally in exception
Finally represents the code to be executed whether or not there is an exception. In other words, no matter whether the previous code is executed correctly or not, the executed code must be written in finally. For example, close the file.
try: f = open('test.txt', 'r') except Exception as result: f = open('test.txt', 'w') else: print('Nothing unusual. I'm so happy') finally: # It is generally used to close all open resources f.close()
(6) Summary
The complete structure of exception handling is as follows:
try sentence try: Code block (statement with possible error) except Exception type as Exception name: Code block (how to deal with errors) except Exception type as Exception name: Code block (how to deal with errors) except Exception type as Exception name: Code block (how to deal with errors) else: Code block (statement to be executed when there is no error) finally: Code block (this code block will always execute)
explain:
- Try must be written. You can put the possible error code into the try statement, so that if the code has no error, it will execute normally. If an error occurs, the code in the expect clause will be executed, so that we can handle the exception through the code to avoid the termination of the whole program due to an exception.
- else statement is OK or not.
- except and finally have at least one.