First, what is an exception
During program execution, it may affect the normal execution of a program, and in general, an exception occurs when a program is not properly handled by Python
When a Python script exception occurs, we need to capture and process him, or the program terminates execution
Second, exception handling
You can use the Try/except statement to catch an exception.
The try/except statement is used to detect errors in a try statement block, allowing the except statement to catch exception information and handle it.
If you do not want to end your program when an exception occurs, simply capture it in a try.
Third, catch the exception
Try works by starting a try statement, and Python is tagged in the context of the current program so that when an exception occurs, it can go back here, the TRY clause executes first, and what happens next depends on whether an exception occurs at execution time.
- If an exception occurs when the statement after the try is executed, Python jumps back to the try and executes the first except clause that matches the exception, and the control flow passes through the entire try statement (unless a new exception is thrown when the exception is handled).
- If an exception occurs in the statement after the try, but there is no matching except clause, the exception will be submitted to the upper try, or to the top of the program (This will end the program and print the default error message).
- If no exception occurs when the TRY clause executes, Python executes the statement after the Else statement (if there is else), and then the control flow passes through the entire try statement.
1. Use except without any exception type.
Try : normal operation ......... ........ except : An exception occurred, execution of this code ... ...... ..... Else : If there is no exception to execute this piece of code
2. Use the same except statement to handle multiple exception information
Try : normal operation ......... ........ except (exception1[, exception2[,... Exceptionn]]): The occurrence of one of the above multiple exceptions, the execution of this piece of code ....... Else : If there is no exception to execute this piece of code
3. The Try-finally statement executes the final code regardless of whether an exception occurs.
Try :< statement >finally:< statement > # always executes when exiting a try
"Code Learning" PYTHON exception handling