Home  >  Article  >  Backend Development  >  About exceptions in Python (Exception)

About exceptions in Python (Exception)

不言
不言Original
2018-04-24 16:14:493544browse

The content of this article is about exceptions in Python, which has a certain reference value. Now I share it with you. Friends in need can refer to it.

Exceptions refer to exceptions in the program. , violation conditions. The exception mechanism refers to the program's handling method after an error occurs in the program. When an error occurs, the execution flow of the program changes and the control of the program is transferred to exception handling. The following article mainly summarizes relevant information about exceptions in Python. Friends in need can refer to it.

Preface

Exception class is a commonly used exception class, which includes StandardError, StopIteration, GeneratorExit, Warning and other exception classes. Exceptions in python are created using inheritance structures. Base class exceptions can be captured in the exception handler, or various subclass exceptions can be captured. Exceptions are captured using the try...except statement in python, and the exception clause is defined after the try clause. .

Exception handling in Python

The statement structure of exception handling

try:
 <statements>  #运行try语句块,并试图捕获异常
except <name1>:
 <statements>  #如果name1异常发现,那么执行该语句块。
except (name2, name3):
 <statements>  #如果元组内的任意异常发生,那么捕获它
except <name4> as <variable>:
 <statements>  #如果name4异常发生,那么进入该语句块,并把异常实例命名为variable
except:
 <statements>  #发生了以上所有列出的异常之外的异常
else:
<statements>   #如果没有异常发生,那么执行该语句块
finally:
 <statement>   #无论是否有异常发生,均会执行该语句块。

Explanation

  • ##else and finally are optional, there may be 0 or more except, but if an else occurs, 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 is activated at any given moment. Once an exception is caught by an except clause somewhere in the program, it is dead unless it is reraised by another raise statement or an error.

raise statement

The raise statement is used to manually throw an exception. There are several calling formats:

  • raise #The instance can be created before the raise statement or in the raise statement.

  • #raise #Python will implicitly create an instance of the class

  • raise name(value) #Provide additional information while throwing an exception value

  • #raise # Rethrow the latest exception

  • raise exception from E


For example:


Throw a

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

When using from, the second expression specifies another exception class or instance, which will be attached to the

__cause__ attribute that raised the exception. If the exception raised is not caught, Python will print the exception as part of the standard error message:

For example, the following code:

try:
 1/0
except Exception as E:
 raise TypeError(&#39;bad input&#39;) from E

The execution result is as follows:

Traceback (most recent call last):
 File "hh.py", line 2, in <module>
 1/0
ZeropisionError: pision by zero

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

Traceback (most recent call last):
 File "hh.py", line 4, in <module>
 raise TypeError(&#39;bad input&#39;) from E
TypeError: bad input

assert statement

assert is mainly used to make assertions , usually used more in unit testing, will be introduced later.

with...as statement

The with statement supports a richer object-based protocol and can define support for entry and exit actions for code blocks.


The requirements for the environment management protocol corresponding to the with statement are as follows:

  • The environment manager must have

    __enter__ and __exit__method.

  • ##          
__enter__

The method will be run during initialization. If there is an ass, the return value of the __enter__ function will be assigned to The variables in the as clause, otherwise, are discarded directly.
The code nested in the code block will be executed.


If the with code block raises an exception, the

__exit__(type,value,traceback)

method will be called (with exception details). These are also the same values ​​returned by sys.exc_info. If this method returns false, the exception is re-raised. Otherwise, it terminates abnormally. Under normal circumstances, exceptions should be re-raised so that they can be passed outside the with statement.
If the with code block does not throw an exception, the

__exit__

method will still be called, and its type, value and traceback parameters will be passed as None.
The following is a simple custom context management class.

class Block:
 def __enter__(self):
  print(&#39;entering to the block&#39;)
  return self
 
 def prt(self, args):
  print(&#39;this is the block we do %s&#39; % args)

 def __exit__(self,exc_type, exc_value, exc_tb):
  if exc_type is None:
   print(&#39;exit normally without exception&#39;)
  else:
   print(&#39;found exception: %s, and detailed info is %s&#39; % (exc_type, exc_value))
  return False

with Block() as b:
 b.prt(&#39;actual work!&#39;)
 raise ValueError(&#39;wrong&#39;)

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


Without canceling the raise statement, the running result is as follows:

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

Exception handler


If an exception occurs, a tuple containing 3 elements can be returned by calling the

sys.exc_info()

function. The first element is the class that raised the exception, and the second is the instance that was actually raised. The third element, the traceback object, represents the stack of calls when the exception originally occurred. If everything is normal, 3 None will be returned.

Exception defined in Python’s Builtins module


|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|

Related recommendations:


Detailed picture and text explanation of python exception handling method

The above is the detailed content of About exceptions in Python (Exception). For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn