An exception is when the syntax is correct , An error when the program runs is an exception .
Catalog
Capture exception
Catch multiple exceptions
Custom exception
try...except...
try:
print("....")
except IOError:
pass
try In the middle is the code that may cause exceptions . When an error occurs , Jump to except Run seven methods to handle exceptions .
If you want to pass once except Multiple exceptions can be caught in the form of a tuple
try:
print("...") # Code
except (IOError,NameError):
pass
Or handle different exceptions differently
try:
ptint("....")
except NameError:
print("nameerror")
except IOError:
print("IOError")
notes : The exception of the parent class should be placed after its child class , Otherwise, there will never be subclass exception handling
in addition , You can also use try...except...else sentence , When try When there is no exception in the statement in ,else The code in will be executed . You can also else Followed by finally,finally The statement in , No matter try It will be executed whether there is any exception in .
Custom exception Class inheritance since Exception class , Can inherit directly , Or indirectly .
Method 1 : Call directly