From the official website: docs.python.org/zh-cn/3.7/t…
Try... expect... The else (optional)
while True:
try:
user_input = int(input('Please enter a number and press Enter:'))
break
# except can use multiple exception classes, passing (RuntimeError, TypeError, NameError) as tuples followed by the variable name, which is equivalent to assigning the found exception to the variable err
except ValueError as err:
print("This is not a valid number. Please try again.", err)
else:
print('Execute else statement only if no exception is found')
Raise Is used to raise an exception
# raise NameError('jobi')
User-defined exceptions need to inherit the Exception class; Most exceptions are defined with names that end in "Error," similar to the naming of standard exceptions.
class CustomError(Exception) :
"""Base class for exceptions in this module."""
pass
# Define the cleanup operation: finally, must be its own statement
try:
raise KeyboardInterrupt
finally:
print("Found an exception and tried it.")
Copy the code