Python exception handling
1. Exception handling method
Put the code segment that needs to be processed under try, and then write the except segment code as needed. else and finally are optional processing. Else will be executed when there is no exception, and finally will be executed. When throwing an exception with raise, you can define the content of the exception description yourself.
2. Code execution order
The first exception detected in the content of try will be thrown, and it will jump directly to the except section for sequential detection. Since subclass exceptions can be treated as parent class exceptions, the subclass exceptions in the except section should be written in front of the parent class exceptions to prevent overwriting.
3. Custom exception
The exception itself is a class, and users can customize exceptions by inheriting from Python's own exception types.
4. One usage
try:
with open(r'D:\python','a+') as e:
e.seek(0)
pass
except:
pass
#Exception handling
try:
print(name) #NameError exception
l1 = [1,3,5]
print(l1[5]) #IndexError exception,
a = int(input("Please enter a three-digit number: "))
if a < 100 : #Throw an exception by yourself
raise ValueError("The input value is too small")
except NameError as ne: #After capturing, jump directly to finally
print("An exception occurred", ne)
except ValueError as ve: #Define the exception yourself Content
print(ve)
except: #The exceptions not above will be captured here
print("No exceptions are considered")
else: #Executed when there are no exceptions, but no
print("No exceptions have occurred")
finally: #No matter what the situation will be executed
print("Executed")