Exceptions refer to exceptions in programs and violations. The exception mechanism refers to the processing method of the program after an error occurs. When an error occurs, the execution process of the program changes, and the control of the program is transferred to exception handling. The following article summarizes the relevant information about exceptions in Python. For more information, see. Exceptions refer to exceptions in programs and violations. The exception mechanism refers to the processing method of the program after an error occurs. When an error occurs, the execution process of the program changes, and the control of the program is transferred to exception handling. The following article summarizes the relevant information about exceptions in Python. For more information, see.
Preface
Exception classes are common Exception classes, including StandardError, StopIteration, GeneratorExit, and Warning. Exceptions in python are created using the inheritance structure. you can capture the basic class exceptions in the exception handling program or various subclass exceptions. in python, try... when the try clause captures exceptions, the exception clause is defined after the try clause.
Exception handling in Python
Statement structure for exception handling
Try:
# Run the try statement block and try to catch the exception limit T
:
# If name1 is abnormal, execute this statement block. T (name2, name3 ):
# If any exception occurs in the Meta Group, capture it to fail t
As
:
# If a name4 exception occurs, enter the statement block and name the exception instance variable0000t:
# Else except all the exceptions listed above:
# If No exception occurs, execute the statement block finally:
# This statement block is executed no matter whether an exception occurs.
Description
Else and finally are optional, and there may be 0 or more slave T. However, if one else appears, there must be at least one slave T.
No matter how you specify exceptions, exceptions are always identified by instance objects and most of the time they are activated at any given time. Once an exception is captured by a distinct T clause somewhere in the program, it will die unless it is re-triggered by another raise statement or error.
Raise statement
The raise statement is used to manually throw an exception. the following call formats are available:
Raise # you can create this instance before the raise statement or in the raise statement.
Raise # Python will implicitly create class instances
Raise name (value) # provides additional information value when an exception is thrown
Raise # throw the last exception
Raise exception from E
For example:
ThrowValueError: raise ValueError('we can only accept positive values')
When using from, the second expression specifies another exception class or instance, which will be appended to__cause__
Attribute. If the exception is not captured, Python prints the exception as part of the standard error message:
For example, the following code:
try: 1/0except Exception as E: raise TypeError('bad input') from E
The execution result is as follows:
Traceback (most recent call last): File "hh.py", line 2, in
1/0ZeropisionError: pision by zeroThe above exception was the direct cause of the following exception:Traceback (most recent call last): File "hh.py", line 4, in
raise TypeError('bad input') from ETypeError: bad input
Assert statement
Assert is mainly used for assertions. it is usually used in unit tests and will be introduced later.
With... as statement
The with statement supports richer object-based protocols, and supports entry and exit actions for code blocks.
The environment management protocol requirements for the with statement are as follows:
__enter__
The method will run during initialization. if the ass sub-is in,__enter__
The return value of the function is assigned to the variables in the as clause. Otherwise, the variables are discarded directly.
The nested code in the code block is executed.
If the with code block causes an exception,__exit__(type,value,traceback)
The method will be called (with exception details ). These are the same values returned by sys. exc_info. if the returned value of this method is false, the exception will be thrown again. Otherwise, the exception will be terminated. Under normal circumstances, an exception should be thrown again so that it can be passed out of the with statement.
If the with code block does not cause an exception,__exit__
The method is still called, and its type, value, and traceback parameters are all passed as None.
The following is a simple custom context management class.
class Block: def __enter__(self): print('entering to the block') return self def prt(self, args): print('this is the block we do %s' % args) def __exit__(self,exc_type, exc_value, exc_tb): if exc_type is None: print('exit normally without exception') else: print('found exception: %s, and detailed info is %s' % (exc_type, exc_value)) return Falsewith Block() as b: b.prt('actual work!') raise ValueError('wrong')
If you log out of the preceding raise statement, it exits normally.
If the raise statement is not deregistered, the running result is as follows:
entering to the blockthis is the block we do actual work!found exception:
, and detailed info is wrongTraceback (most recent call last): File "hh.py", line 18, in
raise ValueError('wrong')ValueError: wrong
Exception processor
If an exception occurs, callsys.exc_info()
Function, which returns a triple containing three elements. The first element is the exception class, the second is the actual instance, and the third element is the traceback object, which represents the Stack called when the exception first occurred. If everything is normal, three None are returned.
Exception defined in the Builtins module of Python
|Exception Name|Description||BaseException|Root class for all exceptions|| SystemExit|Request termination of Python interpreter||KeyboardInterrupt|User interrupted execution (usually by pressing Ctrl+C)||Exception|Root class for regular exceptions|| StopIteration|Iteration has no further values|| GeneratorExit|Exception sent to generator to tell it to quit|| SystemExit|Request termination of Python interpreter|| StandardError|Base class for all standard built-in exceptions|| ArithmeticError|Base class for all numeric calculation errors|| FloatingPointError|Error in floating point calculation|| OverflowError|Calculation exceeded maximum limit for numerical type|| ZeropisionError|pision (or modulus) by zero error (all numeric types)|| AssertionError|Failure of assert statement|| AttributeError|No such object attribute|| EOFError|End-of-file marker reached without input from built-in|| EnvironmentError|Base class for operating system environment errors|| IOError|Failure of input/output operation|| OSError|Operating system error|| WindowsError|MS Windows system call failure|| ImportError|Failure to import module or object|| KeyboardInterrupt|User interrupted execution (usually by pressing Ctrl+C)|| LookupError|Base class for invalid data lookup errors|| IndexError|No such index in sequence|| KeyError|No such key in mapping|| MemoryError|Out-of-memory error (non-fatal to Python interpreter)|| NameError|Undeclared/uninitialized object(non-attribute)|| UnboundLocalError|Access of an uninitialized local variable|| ReferenceError|Weak reference tried to access a garbage collected object|| RuntimeError|Generic default error during execution|| NotImplementedError|Unimplemented method|| SyntaxError|Error in Python syntax|| IndentationError|Improper indentation|| TabErrorg|Improper mixture of TABs and spaces|| SystemError|Generic interpreter system error|| TypeError|Invalid operation for type|| ValueError|Invalid argument given|| UnicodeError|Unicode-related error|| UnicodeDecodeError|Unicode error during decoding|| UnicodeEncodeError|Unicode error during encoding|| UnicodeTranslate Error|Unicode error during translation|| Warning|Root class for all warnings|| DeprecationWarning|Warning about deprecated features|| FutureWarning|Warning about constructs that will change semantically in the future|| OverflowWarning|Old warning for auto-long upgrade|| PendingDeprecation Warning|Warning about features that will be deprecated in the future|| RuntimeWarning|Warning about dubious runtime behavior|| SyntaxWarning|Warning about dubious syntax|| UserWarning|Warning generated by user code|