Detailed Explanation of python Exception Catch and Remedy Example

  • 2021-11-13 02:19:28
  • OfStack

1. Catch specific exceptions

The first qualified except statement is executed to report the error. If only an error is reported, the program will still stop.


a = 0
try:
    b = 5/a
except ZeroDivisionError:
    print('Error: a Cannot be for 0')
except ValueError:
    print('Error:  Invalid parameter passed in ')

2. Catch all exceptions

Exception after the except statement indicates that any exception type is caught.


a = 0
try:
    b = 5/a
except Exception:
    print('a Cannot be for 0')

3. Abnormal remedy

Possible exceptions are remedied after the except statement, such as manually specifying the file address when the default file address cannot be found.


a = 0
try:
    b = 5/a
except:
    b = 0

Extension of knowledge points:

Built-in hierarchy of exception classes

BaseException # Base class for all exceptions
+--SystemExit interpreter requests exit
+--KeyboardInterrupt # User interrupts execution (typically enter ^ C)
+--GeneratorExit # Generator (generator) has an exception to notify exit
+--Base class for Exception # General exceptions
+--StopIteration # Iterator has no more values
+--StopAsyncIteration # must be raised by the __anext__ () method of the asynchronous iterator object to stop the iteration
+--ArithmeticError # Base class for built-in exceptions thrown by various arithmetic errors
+--FloatingPointError # Floating-point calculation error
+--OverflowError # Numeric result too large to represent
+--ZeroDivisionError # divide (or modulo) zero (all data types)
+--AssertionError # Raised when an assert statement fails
+--AttributeError # Attribute reference or assignment failed
Raised when +--BufferError # fails to perform buffer-related operations
+--EOFError # Raised when the input () function meets the end of file condition (EOF) without reading any data
+--ImportError # Failed to import module/object
+--ModuleNotFoundError # Unable to find module or found None in sys. modules
+--Base class for exceptions thrown when a key or index used on an LookupError # map or sequence is invalid
This index is not in the +--IndexError # sequence (index)
+--This key is not in the KeyError # mapping
+--MemoryError # Memory overflow error (not fatal to Python interpreter)
+--NameError # Undeclared/initialized object (no properties)
+--UnboundLocalError # Access uninitialized local variables
+--OSError # Operating System Error, EnvironmentError, IOError, WindowsError, socket. error, select. error and mmap. error have been merged into OSError, constructor may return subclasses
The +--BlockingIOError # operation sets the blocking object (e. g. socket) to a non-blocking operation
+--ChildProcessError # Operation failed on child process
+--Base class for ConnectionError # Connection-related exceptions
+--BrokenPipeError # Attempt to write to a pipe when the other 1 end is closed or attempt to write to a socket where writing is closed
+--ConnectionAbortedError # Connection attempt aborted by peer
+--ConnectionRefusedError # Connection attempt rejected by peer
+--ConnectionResetError # Connection reset by peer
+--FileExistsError # Create an existing file or directory
+--FileNotFoundError # Request a file or directory that does not exist
+--InterruptedError # system call interrupted by input signal
+--IsADirectoryError # Request file operations on a directory (for example, os. remove ())
+--NotADirectoryError # Request directory operations on things that are not directories (e.g. os. listdir ())
+--PermissionError # attempts to run an operation without sufficient access
+--ProcessLookupError # The given process does not exist
+--TimeoutError # System functions time out at the system level
+--The weak reference created by the ReferenceError # weakref. proxy () function attempts to access an object that has been garbage collected
+--RuntimeError # Triggered when an error is detected that does not belong to any other category
+--NotImplementedError # In a user-defined base class, an abstract method requires a derived class to override the method or the class under development indicates that the actual implementation still needs to be added
+--RecursionError # Interpreter Detects Exceeding Maximum Recursive Depth
+--SyntaxError # Python syntax error
+--IndentationError # Indent error
+--TabError # Tab mixed with spaces
+--SystemError # Interpreter Found Internal Error
+--TypeError # Operation or function applied to an object of inappropriate type
+--ValueError # An operation or function receives an argument of the correct type but with an inappropriate value
+--UnicodeError # Encoding or decoding error associated with Unicode occurred
+--UnicodeDecodeError # Unicode decoding error
+--UnicodeEncodeError # Unicode encoding error
+--UnicodeTranslateError # Unicode transcoding error
+--Base class for Warning # Warnings
+--DeprecationWarning # Base class for warnings about deprecated features
+--PendingDeprecationWarning # Base class for warnings about deprecated features
+--RuntimeWarning # Base class for warnings about suspicious runtime behavior
+--SyntaxWarning # Base class for suspicious syntax warnings
+--Base class for UserWarning # User code to generate warnings
+--Base class for FutureWarning # Warnings about deprecated features
+--ImportWarning # Base class for warnings about possible errors when importing modules
+--UnicodeWarning # Base class for Unicode-related warnings
+--BytesWarning # Base class for bytes and bytearray related warnings
+--ResourceWarning # Base class for resource usage related warnings. Ignored by default warning filter.


Related articles: