Understand Python's exception mechanism

coldplay.xixi
Release: 2021-03-10 10:00:33
forward
2939 people have browsed it

Foreword: When I was working before, I used python to complete a command line window that used the serial port to send SCPI and interact with the microcontroller. When implementing the function, I found that python was used to process the data. The result, whether it is the return of the final correct value or the return of an error value, can be directly returned to the main interface. Obviously it is not possible to directly return data with different meanings, so an exception mechanism is used to handle data with wrong values. Because I didn’t know much about anomalies before, I checked some information here and compiled a few notes.

Understand Python's exception mechanism

Article Directory

  • 1. Understanding of exceptions
    • 1. What is an exception?
    • 2. The difference between errors and exceptions
    • 3. Common types of python exceptions
  • 2. python’s five major exception handling mechanisms
    • 1. Default exception handling mechanism
    • 2. try....except....processing mechanism
    • 3. try...except...finally..... processing mechanism
    • 4. assert assertion processing mechanism
    • 5. with...as processing mechanism
  • 3. python exception customization
    • 1.Exception customization
    • 2.Exception throwing raise
    • 3. Exception catching
  • 4. Precautions for using exceptions
    • 1. Don’t rely too much on the exception mechanism
    • 2. Don’t Introducing too much code into the try block
    • 3. Don’t ignore caught exceptions
  • Summary

(Free learning recommendation: python video tutorial)

1. Understanding of exceptions

1. What is abnormality?

 Abnormality means "different from normal conditions". What is normal? Normal means that when the interpreter interprets the code, the code we write conforms to the rules defined by the interpreter, which is normal. When the interpreter finds that a certain piece of code conforms to the grammar but may be abnormal , the interpreter will issue an event to interrupt the normal execution of the program. This interrupt signal is an Exception signal. Therefore, the overall explanation is that when the interpreter detects an error in the program, an exception will be generated. If the program does not handle it, the exception will be thrown and the program will terminate . We can write an int ("m") in a blank .py file, and the result after running is as follows.
Understand Pythons exception mechanism

This string of fonts is a series of error messages thrown by the interpreter, because the parameters passed in int() only support numeric strings and numbers. Obviously 'm' does not belong to numbers. The input string parameter is wrong, so the interpreter reports a "valueError" error.

2. The difference between errors and exceptions

 Overview of Python errors: It refers to syntax or logic errors before the code is run. Take regular syntax errors as an example. When the code we write cannot pass the syntax test, a syntax error will appear directly. It must be corrected before the program is executed. Otherwise, the code written will be meaningless, the code will not run, and it will not be able to Captured. For example, if a = 1 print("hello") is entered in the .py file, the output result is as follows:

  Traceback (most recent call last):
  	File "E:/Test_code/test.py",line 1
    	if a = 1 print("hello")
                ^SyntaxError: invalid syntax
Copy after login

The function print() was found to have an error, which is that there is a colon missing in front of it: , So the parser will reproduce the line of code with the syntax error and use a small "arrow" to point to the first error detected in the line, so we can directly find the corresponding position and modify its syntax. Of course, in addition to grammatical errors, there are also many program crash errors, such as memory overflow, etc. Such errors are often relatively hidden.
 Comparing to errors, Python exceptions mainly occur when the program encounters logical or algorithmic problems during the execution of the program. If the interpreter can handle it, then there is no problem. If it cannot handle it, the program will be terminated directly. , the exception will be thrown, such as the int('m') example in the first point, because the parameter is passed incorrectly, causing a program error. There are all kinds of exceptions caused by logic. Fortunately, our interpreter has built-in various types of exceptions, allowing us to know what kind of exceptions occur, so that we can "prescribe the right medicine".
 One thing to note here is that the above syntax errors are identifiable errors, so the interpreter will also throw a SyntaxError exception message by default to feed back to the programmer. So in essence, most errors can be output and printed, but because the error code does not run, it cannot be handled, so capturing the error exception information becomes meaningless.

3. Common python exception types

Here are the most common exception types when we write code. If you encounter other types of exceptions, of course, choose white It’s time~

##ArithmeticErrorBase class for all numerical calculation errorsFloatingPointError Floating point calculation errorOverflowErrorNumerical operation exceeds the maximum limitZeropisionErrorDivision (or modulo) zero (all data types)AssertionErrorAssertion statement failed##AttributeError EOFErrorEnvironmentError IOErrorOSErrorWindowsErrorImportErrorLookupErrorIndexErrorKeyErrorMemoryErrorNameErrorUnboundLocalErrorReferenceErrorRuntimeErrorNotImplementedErrorSyntaxError PythonIndentationError TabError TabSystemError##TypeErrorInvalid operation on typeValueErrorInvalid parameter passed inUnicodeError UnicodeRelated errorsUnicodeDecodeError UnicodeError during decodingUnicodeEncodeError UnicodeError while encodingUnicodeTranslateError UnicodeError while convertingWarningBasic class for warnings DeprecationWarningWarning about deprecated featuresFutureWarningAbout constructing future semantics There will be a changed warningOverflowWarningOld warning about automatic promotion to long PendingDeprecationWarningWarning about feature being deprecatedRuntimeWarningWarning about suspicious runtime behaviorSyntaxWarningSuspicious syntax warningUserWarningWarning generated by user code

二、python五大异常处理机制

  我们明白了什么是异常后,那么发现异常后怎么处理,便是我们接下来要解决的问题。这里将处理异常的方式总结为五种。

1、默认异常处理机制

  “默认”则说明是解释器默认做出的行为,如果解释器发现异常,并且我们没有对异常进行任何预防,那么程序在执行过程中就会中断程序,调用python默认的异常处理器,并在终端输出异常信息。刚才举过的例子:int(“m”),便是解释器因为发现参数传入异常,这种异常解释器“无能为力”,所以它最后中断了程序,并将错误信息打印输出,告诉码农朋友们:你的程序有bug!!!

2、try…except…处理机制

  我们把可能发生错误的语句放在try语句里,用except来处理异常。每一个try,都必须至少有一个或者多个except。举一个最简单的例子如下,在try访问number的第500个元素,很明显数组越界访问不了,这时候解释器会发出异常信号:IndexError,接着寻找后面是否有对应的异常捕获语句except ,如果有则执行对应的except语句,待except语句执行完毕后,程序将继续往下执行。如果没有对应的except语句,即用户没有处理对应的异常,这时解释器会直接中断程序并将错误信息打印输出

number = 'hello'try:	print(number[500])	#数组越界访问except IndexError:	print("下标越界啦!")except NameError:	print("未声明对象!")print("继续运行...")
Copy after login

输出结果如下,因为解释器发出异常信号是IndexError,所以执行下标越界语句。

下标越界啦!
继续运行...
Copy after login

  为了解锁更多用法,我们再将例子改一下,我们依然在try访问number的第500个元素,造成访问越界错误,这里的except用了as关键字可以获得异常对象,这样子便可获得错误的属性值来输出信息。

number = 'hello'try:	print(number[500])	#数组越界访问except IndexError as e:	print(e)except Exception as e:	#万能异常
	print(e)except:			  	 #默认处理所有异常
	print("所有异常都可处理")print("继续运行...")
Copy after login

输出结果如下所示,会输出系统自带的提示错误:string index out of range,相对于解释器因为异常自己抛出来的一堆红色刺眼的字体,这种看起来舒服多了(能够“运筹帷幄”的异常才是好异常嘛哈哈哈)。另外这里用到“万能异常”Exception,基本所有没处理的异常都可以在此执行。最后一个except表示,如果没有指定异常,则默认处理所有的异常。

string index out of range继续运行...
Copy after login

3、try…except…finally…处理机制

  finally语句块表示,无论异常发生与否,finally中的语句都要执行完毕。也就是可以很霸气的说,无论产生的异常是被except捕获到处理了,还是没被捕获到解释器将错误输出来了,都统统要执行这个finally。还是原来简单的例子加上finally语句块如下,代码如下:

number = 'hello'try:	print(number[500])	#数组越界访问,抛出IndexError异常except IndexError:	print("下标越界啦!")finally:	print("finally!")print("继续运行...")		#运行
Copy after login

结果如下,数据越界访问异常被捕获到后,先执行except 语句块,完毕后接着执行了finally语句块。因为异常被执行,所以后面代码继续运行。

下标越界啦!finally!
继续运行...
Copy after login

  对try语句块进行修改,打印abc变量值,因为abc变量没定义,所以会出现不会被捕获的NameError异常信号,代码如下所示:

number = 'hello'try:	print(abc)	#变量未被定义,抛出NameError异常except IndexError:	print("下标越界啦!")finally:	print("finally!")print("继续运行...")	#不运行
Copy after login

结果如下,因为NameError异常信号没法被处理,所以解释器将程序中断,并将错误信息输出,但这过程中依然会执行finally语句块的内容。因为程序被迫中断了,所以后面代码不运行。

finally!	#异常没被捕获,也执行了finallyTraceback (most recent call last):
	File "E:/Test_code/test.py",line 3,in <module>
   		print("abc")NameError: name &#39;abc&#39; is not defined
Copy after login
Copy after login

  理解到这里,相信:try…finally…这种机制应该也不难理解了,因为省略了except 捕获异常机制,所以异常不可能被处理,解释器会将程序中断,并将错误信息输出,但finally语句块的内容依然会被执行。例子代码如下:

number = &#39;hello&#39;try:	print(abc)	#变量未被定义,抛出NameError异常finally:	print("finally!")print("继续运行...")
Copy after login

运行结果:

finally!	#异常没被捕获,也执行了finallyTraceback (most recent call last):
	File "E:/Test_code/test.py",line 3,in <module>
   		print("abc")NameError: name &#39;abc&#39; is not defined
Copy after login
Copy after login

4、assert断言处理机制

  assert语句先判断assert后面紧跟的语句是True还是False,如果是True则继续往下执行语句,如果是False则中断程序,将错误信息输出。

assert 1 == 1 	#为True正常运行assert 1 == 2	#为False,终止程序,错误信息输出
Copy after login

5、with…as处理机制

  with…as一般常用在文件处理上,我们平时在使用类似文件的流对象时,使用完毕后要调用close方法关闭,很麻烦,这里with…as语句提供了一个非常方便且人性的替代方法,即使突发情况也能正常关闭文件。举个例子代码如下,open打开文件后将返回的文件流对象赋值给fd,然后在with语句块中使用。

with open(&#39;e:/test.txt&#39;,&#39;r&#39;) as fd:
	fd.read()
	print(abc)	#变量未被定义,程序终止,错误信息输出print("继续运行...")
Copy after login

  正常情况下,这里的with语句块完毕之后,会自动关闭文件。但如果with语句执行中发生异常,如代码中的变量未定义异常,则会采用默认异常处理机制,程序终止,错误信息输出,后面代码不被运行,文件也会正常关闭。

三、python异常自定义

  说了这么多异常的使用,终于可以回到我前言所说的在实际项目中存在的问题,即错误码的返回和数值的返回是冲突的(因为错误码也是数值),这时候便可以用异常的抛出和捕获来完成错误码的传递,即try和except 。但系统发生异常时抛出的是系统本身定义好的异常类型,跟自己的错误码又有何关系?这就是我接下来要说的内容:如何定义自己的异常并且能够被except 所捕获

1、异常自定义

  实际开发中,有时候系统提供的异常类型往往都不能满足开发的需求。这时候就要使用到异常的自定义啦,你可以通过创建一个新的异常类来拥有自己的异常。自己定义的异常类继承自 Exception 类,可以直接继承,或者间接继承。栗子举起来:

class MyException(Exception):
    &#39;&#39;&#39;自定义的异常类&#39;&#39;&#39;
    def __init__(self, error_num):	#异常类对象的初始化属性
        self.error_num = error_num    def __str__(self):				#返回异常类对象说明信息
        err_info = [&#39;超时错误&#39;,&#39;接收错误&#39;]
        return err_info[self.error_num]
Copy after login

  该类继承自Exception 类,并且新类的名字为MyException,这跟前面我们一直在用的IndexError这个异常类一样,都是继承自Exception 类。__init__为构造函数,当我们创建对象时便会自动调用,__str__为对象说明信息函数,当使用print输出对象的时候,只要自己定义了__str__方法,那么就会打印从在这个方法中return的数据。
  即print(MyException(0))时,便可打印“超时错误”这个字符串,print(MyException(1))时,便可打印“接收错误”这个字符串,心细的你应该可以理解,MyException(x)为临时对象(x是传入错误码参数,这里只定义了0和1),与a = MyException(x),a为对象一个样子 。 这里有一个好玩的说法,在python中方法名如果是__xxxx__()的,那么就有特殊的功能,因此叫做“魔法”方法。

2、异常抛出raise

  现在我们自己定义的错误定义好了(上面的MyException),怎么能像IndexError一样让except捕获到呢?于是乎raise关键字派上用场。我们在异常机制中用try…except时,一般都是将可能产生的错误代码放到try语句块中,这时出现异常则系统便会自动将其抛出,比如IndexError,这样except就能捕获到,所以我们只要将自定义的异常在需要的时候将其抛出即可。
  raise 唯一的一个参数指定了要被抛出的异常。它必须是一个异常的实例或者是异常的类(也就是 Exception 的子类),那么我们刚刚定义的异常类就可以用啦,举个简单例子:

try:
    raise MyException(0)	# 自己定义的错误类,将错误码为0的错误抛出except MyException as e:
    print(e) 	  			# 输出的是__str__返回的内容,即“超时错误”
Copy after login

  这里我直接将自己定义的错误抛出,…as e就是把得到的错误当成对象e,这样才可以访问其属性和方法。因为自己定义的错误中可以支持多个错误码(本质还是MyException这个错误),所以便可实现传入不同错误码就可打印不同错误信息。

3、异常捕获

  只要我们在try中将错误raise出来,except就可以捕获到(当然,异常必须是Exception 子类才能被捕获),将前面两个例子整合起来,代码如下:

&#39;&#39;&#39;错误码:0代表超时错误,1代表接收错误&#39;&#39;&#39;class MyException(Exception):
    &#39;&#39;&#39;自定义的异常类&#39;&#39;&#39;
    def __init__(self, error_num):	# 异常类对象的初始化属性
        self.error_num= error_num    def __str__(self):				# 返回异常类对象指定错误码的信息
        err_info = [&#39;超时错误&#39;,&#39;接收错误&#39;]
        return err_info[self.error_num]def fun()
	raise MyException(1) 			# 抛出异常对象,传入错误码1def demo_main():
    try:
        fun()
    except MyException as ex:		# 这里要使用MyException进行捕获,对象为ex
        print(ex) 	   				# 输出的是__str__部分返回的内容,即“接收错误”
        print(ex.error_num) 		# 输出的是__init__中定义的error_num,即1demo_main()							#此处开始运行
Copy after login

  代码从demo_main函数开始执行,进入try语句块,语句块中的fun()函数模拟代码运行失败时raise 自定义的异常,except 正常接收后通过as 关键字得到异常对象,访问该异常对象,便可正常输出自定义的异常信息和自定义的错误码。

四、异常使用注意事项

此注意事项参考博文:异常机制使用细则.

1、不要太依赖异常机制

  python 的异常机制非常方便,对于信息的传递中十分好用(这里信息的传递主要有三种,参数传递,全局变量传递,以及异常机制传递),但滥用异常机制也会带来一些负面影响。过度使用异常主要表现在两个方面:①把异常和普通错误混淆在一起,不再编写任何错误处理代码,而是以简单地引发异常来代苦所有的错误处理。②使用异常处理来代替流程控制。例子如下:

buf = "hello"#例1:使用异常处理来遍历arr数组的每个元素try:
    i = 0    
    while True:
        print (buf [i])
        i += 1except:
    pass#例2:使用流程控制避免下标访问异常i = 0while i < len(buf ):
    print(buf [i])
    i += 1
Copy after login

  例1中假如循环过度便会下标访问异常,这时候把错误抛出,再进行一系列处理,显然是不可取的,因为异常机制的效率比正常的流程控制效率差,显然例2中简单的业务流程就可以避开这种错误。所以不要熟悉了异常的使用方法后,遇到这种简单逻辑,便不管三七二十一引发异常后再进行解决。对于完全己知的错误和普通的错误,应该编写处理这种错误的代码,增加程序的健壮性。只有对于外部的、不能确定和预知的运行时错误才使用异常

2、不要在 try 块中引入太多的代码

Placing a large amount of code in the try block seems "simple" and the code framework is easy to understand. However, because the code in the try block is too large and the business is too complex, will cause the code to appear in the try block. The possibility of anomalies is greatly increased, which makes it more difficult to analyze the causes of anomalies.
- And when the block is too large, it is inevitable to follow the try block with a large number of except blocks to provide different processing logic for different exceptions. If the same try block is followed by a large number of except blocks, you need to analyze the logical relationship between them, which increases the programming complexity. Therefore, You can divide the large try block into multiple small blocks, and then capture and handle exceptions respectively.

3. Don’t ignore caught exceptions

 Don’t ignore exceptions! Now that the exception has been caught, the except block should do something useful and handle and fix the exception. It is inappropriate to leave the entire except block empty, or to just print simple exception information! The specific processing method is:
Handle exceptions. Make appropriate repairs to the exception, and then continue running by bypassing the place where the exception occurred; or use other data to perform calculations instead of the expected method return value; or prompt the user to re-operate. In short, the program should try to repair the exception as much as possible. Allow the program to resume operation.
Re-raise a new exception. Do everything that can be done in the current running environment as much as possible, then translate the exception, package the exception into an exception of the current layer, and re-pass it to the upper-layer caller.
Handle exceptions at the appropriate layer
. If the current layer does not know how to handle the exception, do not use the except statement in the current layer to catch the exception, and let the upper-layer caller be responsible for handling the exception.

Summary

This article starts with the system default exceptions, explains what exceptions are and summarizes the common exception classes in the system, and then writes how to customize exceptions. From the definition of exceptions to throwing to getting the definition and use of custom exceptions, and finally summarizes the precautions when using Python exceptions.

Related free learning recommendations: python tutorial(Video)

The above is the detailed content of Understand Python's exception mechanism. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:csdn.net
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
Exception nameName resolution
BaseExceptionAll exceptions Base class
SystemExitInterpreter request to exit
KeyboardInterruptUser interrupts execution (usually Enter ^C)
ExceptionGeneral Error Base Class
StopIterationIterator None More values
GeneratorExitThe generator generates an exception to notify the exit
StandardErrorBase class for all built-in standard exceptions
Object does not have this attribute
No built-in input, EOF flag reached
Base class for operating system errors
Input/output operation failed
Operating system error
System call failed
Import Module/Object failed
Invalid data query base class
In sequence No such index(index)
There is no such key in the map
Memory Overflow error (not fatal to the Python interpreter)
Undeclared/initialized object (no attributes)
Accessing uninitialized local variables
Weak reference attempts to access an object that has been garbage collected
General runtime error
Not yet implemented method
Syntax error
Indentation error
mixed with spaces
General interpreter system error