Python built-in exception
In Python, exceptions are also objects that can be manipulated. BaseException is the base class of all built-in exceptions, but user-defined classes do not directly inherit BaseException. All Exception classes inherit from Exception and are defined in exceptions module. Python automatically puts all Exception names in the built-in namespace, so the program can use exceptions without importing the exceptions module. Once a SystemExit Exception is thrown and not caught, program execution terminates. If an interactive session encounters an uncapped SystemExit Exception, the session terminates.
BaseException # Base class for all exceptions +-- SystemExit # Interpreter requests exit +-- KeyboardInterrupt # User interrupts execution (usually enter ^ C) +-- GeneratorExit # An exception occurred in the generator to notify it to exit +-- Exception # Base class for general exceptions +-- StopIteration # The iterator has no more values +-- StopAsyncIteration # Must pass the of an asynchronous iterator object__ anext__ () method raised to stop the iteration +-- ArithmeticError # Base class for built-in exceptions thrown by various arithmetic errors | +-- FloatingPointError # Floating point calculation error | +-- OverflowError # The numerical result is too large to represent | +-- ZeroDivisionError # Divide (or modulo) zero (all data types) +-- AssertionError # Raised when the assert statement fails +-- AttributeError # Property reference or assignment failed +-- BufferError # Raised when a buffer related operation cannot be performed +-- EOFError # Raised when the input() function reaches the end of file condition (EOF) without reading any data +-- ImportError # Failed to import module / object | +-- ModuleNotFoundError # Cannot find module or None in sys.modules +-- LookupError # The base class of the exception that is thrown when the key or index used on the map or sequence is invalid | +-- IndexError # This index does not exist in the sequence | +-- KeyError # This key is not in the map +-- MemoryError # Memory overflow error (not fatal for Python interpreter) +-- NameError # Object not declared / initialized (no properties) | +-- UnboundLocalError # Accessing uninitialized local variables +-- OSError # Operating system error, EnvironmentError, IOError, WindowsError, socket.error, select.error and mmap.error have been merged into OSError, and the constructor may return subclasses | +-- BlockingIOError # Operation sets the blocking object (e.g. socket) to a non blocking operation | +-- ChildProcessError # The operation on the child process failed | +-- ConnectionError # Base class for connection related exceptions | | +-- BrokenPipeError # An attempt was made to write to a pipe when the other end was closed or to write on a socket that was closed for writing | | +-- ConnectionAbortedError # The connection attempt was aborted by the peer | | +-- ConnectionRefusedError # The connection attempt was rejected by the peer | | +-- ConnectionResetError # Connection reset by peer | +-- FileExistsError # Create an existing file or directory | +-- FileNotFoundError # Request a file or directory that does not exist | +-- InterruptedError # The system call was interrupted by an input signal | +-- IsADirectoryError # Request a file operation on a directory (for example, os.remove()) | +-- NotADirectoryError # Request a directory operation on something that is not a directory (for example, os.listdir()) | +-- PermissionError # An attempt was made to run the operation without sufficient access rights | +-- ProcessLookupError # The given process does not exist | +-- TimeoutError # The system function timed out at the system level +-- ReferenceError # The weak reference created by the weakref.proxy() function attempts to access an object that has been garbage collected +-- RuntimeError # Triggered when an error that does not belong to any other category is detected | +-- NotImplementedError # In the user-defined base class, the abstract method requires the derived class to override the method or the class under development indicates that the actual implementation still needs to be added | +-- RecursionError # The interpreter detected that the maximum recursion depth was exceeded +-- SyntaxError # Python syntax error | +-- IndentationError # Indent error | +-- TabError # Mixing tabs and spaces +-- SystemError # The interpreter found an internal error +-- TypeError # An action or function is applied to an object of an inappropriate type +-- ValueError # The operation or function received an argument of the correct type but with an inappropriate value | +-- UnicodeError # A Unicode related encoding or decoding error has occurred | +-- UnicodeDecodeError # Unicode decoding error | +-- UnicodeEncodeError # Unicode encoding error | +-- UnicodeTranslateError # Unicode transcoding error +-- Warning # Warning base class +-- 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 +-- UserWarning # Base class for user code generation warnings +-- FutureWarning # Base class for warnings about deprecated features +-- ImportWarning # Base class for warnings about possible errors during module import +-- UnicodeWarning # Base class for Unicode related warnings +-- BytesWarning # Base class for warnings related to bytes and byte array +-- ResourceWarning # Base class for warnings related to resource usage. Ignored by default warning filter.
exception handling
Catch multiple exceptions and undecidable exceptions:
else statement
Cross layer call
As long as you define try...except..finally in the main function, you can catch exceptions at different levels
Throw exception
Python uses the raise statement to throw a specified exception. For example:
Define cleanup behavior
1. Clean up actions that will be performed under any circumstances.
Generally, I will write some code to close files and network connections in finally
2. Include except and finally clauses in the same try statement
2 is an example of a more complex version of 1
3. Predefined cleanup behavior
Some objects define standard cleanup behavior. No matter whether the system successfully uses it or not, once it is no longer needed, the standard cleanup behavior will be executed. The keyword with statement can ensure that objects such as files will correctly execute their cleaning methods after use:
improvement:
Logging error (logging module)
(23 messages) Python standard module -- logging_weixin_34149796 blog - CSDN blog
python's built-in logging module can easily record error messages
The logging module is a standard built-in module in Python. It is mainly used to output running logs. You can set the level of output logs (debug, info, warning, error, if level=info,logging.debug does not work, level=warning,logging.debug and logging.info do not work), log saving path, log file rollback, etc; Compared with print, it has the following advantages:
- By setting different log levels, only important information can be output in the release version without displaying a large amount of debugging information;
- print outputs all information to the standard output, which seriously affects developers to view other data from the standard output; logging allows developers to decide where to output information and how to output it;
example