Python common exception handling mechanism

Python's reengineering

1

Default exception handling

**Scenario: **If an error is reported in a certain line of the filled code, the following code will not be executed

02

try...except...

Scenario: If an exception is caught, the code behind will also be executed

03

try..except..finaly

Scenario: The code in the finally statement will be executed regardless of whether it is abnormal or not

04

try...finally...

Scenario: Since there is no exception caught by except, the statement in finally will be executed regardless of whether it is abnormal or not. If there is an exception, the code behind finally will not be executed, otherwise it will be executed.

05

assert

Scenario: If the code behind the assertion is False, interrupt the program and call the default exception handler. When assert True, continue to execute the following steps, assert False and the following code does not execute.

06

with...as..

Scenario: This can be used when the stream object needs to be closed frequently. After the with statement ends, the file will be closed automatically. If the with statement is abnormal, the default exception handler will be called, the file will be closed normally, and the following code will not be executed.

07

Throw exception raise

Syntax: raise [exceptionName [(reason)]]

Scenario: The more detailed the exception after raise, the better to tell the system that there is an exception. The statement after raise will not be executed

ps: The exception thrown in except must be less than the raise exception level and different exception types. If Exception is thrown, the exception in raise will not be output.

08

raise custom exception

**Scenario: **Users can customize the content of the exception

Recommended Posts

Python common exception handling mechanism
Python exception handling
Python garbage collection mechanism
Python error handling method
09. Common modules of Python3
Python runtime exception management solution
Python common data structure collation
2020--Python grammar common knowledge points
Collection of Python Common Modules
Detailed implementation of Python plug-in mechanism
Common errors and solutions in python
Python error handling assert detailed explanation
Several common modes of Python functions
Python's exception concept introduction and handling