Python's exception handling mechanism
Use try...except to catch exceptions
try: # Business implementation code ... except (Error1, Error2, ...) as e: # Handling code after exception ...
Inheritance relationship of exception class
BaseException +-- SystemExit +-- KeyboardInterrupt +-- GeneratorExit +-- Exception +-- StopIteration +-- StopAsyncIteration +-- ArithmeticError | +-- FloatingPointError | +-- OverflowError | +-- ZeroDivisionError +-- AssertionError +-- AttributeError +-- BufferError +-- EOFError +-- ImportError | +-- ModuleNotFoundError +-- LookupError | +-- IndexError | +-- KeyError +-- MemoryError +-- NameError | +-- UnboundLocalError +-- OSError | +-- BlockingIOError | +-- ChildProcessError | +-- ConnectionError | | +-- BrokenPipeError | | +-- ConnectionAbortedError | | +-- ConnectionRefusedError | | +-- ConnectionResetError | +-- FileExistsError | +-- FileNotFoundError | +-- InterruptedError | +-- IsADirectoryError | +-- NotADirectoryError | +-- PermissionError | +-- ProcessLookupError | +-- TimeoutError +-- ReferenceError +-- RuntimeError | +-- NotImplementedError | +-- RecursionError +-- SyntaxError | +-- IndentationError | +-- TabError +-- SystemError +-- TypeError +-- ValueError | +-- UnicodeError | +-- UnicodeDecodeError | +-- UnicodeEncodeError | +-- UnicodeTranslateError +-- Warning +-- DeprecationWarning +-- PendingDeprecationWarning +-- RuntimeWarning +-- SyntaxWarning +-- UserWarning +-- FutureWarning +-- ImportWarning +-- UnicodeWarning +-- BytesWarning +-- ResourceWarning
Access exception information
try: statement except Exception as e: # Error number and details of access exception print(e.args) # Error number of access exception print(e.errno) # Access exception details print(e.strerror)
Block else
s = input('Please enter divisor:') try: result = 20 / int(s) print("20 Divide%s The result is:%g" % (s, result)) except ValueError: print("Wrong value, you must enter a number") except ArithmeticError: print("Arithmetic error, cannot enter 0") else: print("No exception occurred")
Block finally
try: statement except Exception as e: # Exception handling block ... else: # When no exception occurs ... finally: # No matter whether there is an exception or not, it will execute ...
Custom exception handling
Use raise to throw an exception
- When an error occurs in the program, the system will automatically throw an exception. In addition, Python allows programs to use the raise statement to throw their own exceptions
Custom exception class
- Custom exception class
Custom Exception classes should inherit Exception base classes or subclasses of Exception
class MyException(Exception): pass
- Use custom exception class
raise MyException("Custom exception information")