#Python's exception
In the process of program development, it is inevitable to deal with some abnormal situations, such as failure to open the file due to being occupied, transmission failure due to network congestion, etc. In order to ensure the normal operation of the program, exception handling is required.
Python uses try and except to catch exceptions, and finally to specify final actions:
exceptandfinallyare not required, but at least one of them is required- There can be multiple
exceptto handle different types of exceptions
try:
try-block # code to run
except 要捕获的异常类型:
except-block # Executed when an exception occurs in the try-block
finally:
finally-block # will be executed no matter what
Example:
try:
10 / 0
except Exception as e: # Catch the exception of type Exception and assign it to e
print("Caught error that is", e)
Exceptionis the base class of all exception types and can catch all types of exceptions.
#Generate exception
Python uses raise to generate exceptions:
raise Exception('An error')