Summary of the exception of Exception in Python

  • 2020-05-24 05:47:51
  • OfStack


The Exception class is a common exception class, which includes StandardError, StopIteration, GeneratorExit, Warning, and so on. Exceptions in python are created using an inheritance structure. You can catch base class exceptions in an exception handler, as well as various subclass exceptions. python USES try... The except statement catches exceptions, and the exception clause is defined after the try clause.

Exception handling in Python

Statement structure for exception handling

 <statements>  # run try Statement block and attempt to catch the exception 
except <name1>:
 <statements>  # if name1 Exception found, then execute the statement block. 
except (name2, name3):
 <statements>  # If any exception occurs within the tuple, it is caught 
except <name4> as <variable>:
 <statements>  # if name4 When an exception occurs, enter the block and name the exception instance variable
 <statements>  # An exception occurred in addition to all of the exceptions listed above 
<statements>   # If no exception occurs, the statement block is executed 
 <statement>   # The statement block is executed whether or not an exception occurs. 


else and finally are optional, and there may be zero or more except, but if one else appears, there must be at least one except.
No matter how you specify the exception, the exception is always identified by the instance object, and most of the time it is activated at any given moment. Once an exception is caught by an except clause somewhere in the program, it dies unless it is reraised by another raise statement or an error.

raise statement

The raise statement is used to manually throw an exception in the following call formats:

raise # can create this instance before the raise statement or in the raise statement. raise #Python implicitly creates an instance of the class When raise name(value) # throws an exception, provide additional information value raise # throws back the last exception raise exception from E

Such as:

Throw one with additional information ValueError: raise ValueError('we can only accept positive values')

When using from, the second expression specifies another exception class or instance that will be attached to the one that raised the exception __cause__ Properties. If the exception thrown is not caught, Python prints the exception as part 1 of the standard error message:

For example, the following code:

except Exception as E:
 raise TypeError('bad input') from E

The results are as follows:

Traceback (most recent call last):
 File "", line 2, in <module>
ZeroDivisionError: division by zero

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
 File "", line 4, in <module>
 raise TypeError('bad input') from E
TypeError: bad input

assert statement

assert is mainly used for making assertions, usually in unit tests, but we'll talk about it later.

with... as statement

The with statement supports a richer object-based protocol that defines entry and exit actions for code blocks.

The requirements of the environmental management agreement corresponding to the with statement are as follows:

The environment manager must exist __enter__ and __exit__ Methods.

__enter__ The method will be run at the time of initialization, if there are ass children, __enter__ The return value of the function is assigned to the variable in the as clause; otherwise, it is simply discarded.

The nested code in the block is executed.

If an with block throws an exception, __exit__(type,value,traceback) The method is called (with exception details). These are also the same values returned by sys.exc_info. If this method returns a false value, the exception is rethrown. Otherwise, the exception terminates. Normally the exception should be rethrown so that it can be passed outside the with statement.

If the with code block does not throw an exception, __exit__ The method is still called, and its type, value, and traceback arguments are passed as None.

Here 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')
   print('found exception: %s, and detailed info is %s' % (exc_type, exc_value))
  return False

with Block() as b:
 b.prt('actual work!')
 raise ValueError('wrong')

If you log out to the raise statement above, it exits normally.

Without logging off the raise statement, the result is as follows:

entering to the block
this is the block we do actual work!
found exception: <class 'ValueError'>, and detailed info is wrong
Traceback (most recent call last):
 File "", line 18, in <module>
 raise ValueError('wrong')
ValueError: wrong

Exception handler

If an exception occurs, then by calling sys.exc_info() Function that returns a tuple containing three elements. The first element is the class that throws the exception, the second is the actual instance that is thrown, and the third element, the traceback object, represents the stack that was called when the exception first occurred. If the 1 slice is normal, then 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|
|   ZeroDivisionError|Division (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|


The above is the whole content of this article, I hope the content of this article to your study or work can bring 1 definite help, if you have questions you can leave a message to communicate.

Related articles: