abnormal
Python uses exception objects to represent the abnormal state and raises an exception when it encounters an error. When the exception object is not processed (or caught), the program will terminate and display an error message (traceback) .
1. Raise exceptions autonomously
1.1, raise statement
To raise an exception, you can use the raise statement , and a class (must be a subclass of Exception) or instance as a parameter.
Some built-in exception classes | Description |
---|---|
Exception | Almost all exception classes are derived from it |
AttributeError | Raised when referencing a property or assigning a value to it fails |
OSError | Raised when the operating system cannot perform a specified task (such as opening a file), there are multiple subclasses |
IndexError | Raised when using an index that does not exist in the sequence, a subclass of LookupError |
KeyError | Raised when using a key that does not exist in the map, is a subclass of LookupError |
NameError | Raised when the name (variable) cannot be found |
SyntaxError | Raised when the code is incorrect |
TypeError | Raised when a built-in operation or function is used for an object of incorrect type |
ValueError | Raised when a built-in operation or function is used for such an object: its type is correct but the value contained is inappropriate |
ZeroDivisionError | Raised when the second parameter of the division or modulo operation is zero |
1.2, custom exception class
Just like creating other classes, but you must directly or indirectly inherit Execption.
2. Catch the exception
The interesting thing about exceptions is that they can be handled, usually called catching exceptions, using try/except statements .
The exception is propagated from the function to the place where the function is called. If it is not caught here, the exception will propagate to the top level of the program.
2.1. No parameters are provided
After catching the exception, if you want to reraise it (that is, continue to propagate upward), you can call raise without providing any parameters (you can also provide the caught exception explicitly).
2.2. Finally
The finally statement, regardless of whether an exception occurs, the content of the finally statement will be executed .