Exception module in Python

Refer to the book "Python3 from entry to actual combat"

Exception module in Python

1. Basic framework

@Note: When writing a program, if you know that a certain piece of code may cause an exception, but you don't want the program to be terminated by a stack trace, you need to write program code for exception handling.
@You can handle the exceptions that occur through try/except or try/finally statements (or a combination of them). If the exception is processed, the program can proceed.
#模式:
try...except...
try...except...else
try...except...else...finally
try...except...except...else...finally
try...finally
@The basic form is: try...except block, put the code that may cause exceptions in the try clause (program block), if no exception occurs after the try clause is completed, the except block (also called the except clause) ) Continue to execute the following code. If an error occurs during the execution of the code in the try clause and an exception is thrown, the except block (clause) will handle the exception. Once the exception is processed by the except clause, the program will continue to execute from the try...except statement .
	try:
        x = int(input('Enter x '))#输入数并进行强制类型转换
        y = int(input('Enter y '))
        print(x/y)#除数不能为0
        print('x/y结果正常')
    except:
        print("出现了异常!")
    运行结果如下:
    Enter x 0

	Enter y 1
	0.0
	x/y结果正常
	----------------------(再运行一次)------------------------------------
	Enter x 1

	Enter y 0
	出现了异常!

Two, catch specific exceptions

The except clause can catch any type of exception thrown in the try block. Sometimes, you may need to handle different types of exceptions differently, that is, specify the specific exception name after the except keyword. You can use as to give a name to this type of exception object.
	try:
        x = int(input("输入x"))
        y = int(input("输入y"))
        print(x/y)
        print('x/y结果正常')
    except ZeroDivisionError as e:#关于这个异常的名字可以通过解释器终止程序执行
        print("除数不能为0!!!!!!")#的时候看一看是由于什么异常导致的。
    except ValueError as e:
        print("输入类型错误!!!!!")
	
	运行结果如下:
	输入x1

	输入y0
	除数不能为0!!!!!!
	----------------------------(再运行一次)----------------------------
	
	输入xasd
	输入类型错误!!!!!

Three, the order of exception capture

@When the try clause throws an exception, it searches for matching exception handling clauses in order from top to bottom according to the type of the exception. Therefore, special exceptions should be placed first, and more general exceptions should be placed behind. Because if the more general exception is processed first, the subsequent special exception will not be processed.
@Capture the built-in exception at the location: The last except clause captures the exception of the BaseException type, and then all exceptions can be captured. Since Exception is the parent class of most exceptions, Exception can also be used instead of BaseException under normal circumstances.
@You can add an else clause after the last except clause. When no exception occurs, the else clause will be executed automatically, but if an exception occurs, it will not be executed.
	try:
        x = int(input("输入x"))
        y = int(input("输入y"))
        print(x/y)
        print('x/y结果正常')
    except ZeroDivisionError as e:
        print("除数不能为0!!!!!!")
    except Exception as e:
        print("我也不知道是什么错误!!!!!")
    else:
        print("没有任何异常")
    运行结果如下:
	输入xqwewq 
	我也不知道是什么错误!!!!!
	输入x1       #注意这里我没有打空格,是输入x=1,y=2。

	输入y2
	0.5
	x/y结果正常
	没有任何异常

Four, finally clause

@Regardless of whether there is an exception, it will be executed. If an exception occurs, but it has not been processed, when all the codes in finally are executed, the exception will continue to be thrown by the calling function of the upper layer until this If the exception is processed at a certain level, the program will continue to execute, or if the exception has not been processed, the program will terminate
	#写了三个try语句 帮助理解
	try:
        x = 1/1
        print(x)
    finally:
        print("永远执行:")
        
    print   ("-"*60)#分隔
    
    try:
        x = 1/0
        print(x)
    except Exception as e:
        print("除数不能为0")#错误能被处理,后执行了finally语句
    finally:
        print("永远执行:")
        
    print   ("-"*60)#分隔
    
    try:
        x = 1/0
        print(x)
    finally:
        print("永远执行:")#先执行了finally语句
    
    运行结果如下:
    1.0
	永远执行:
	------------------------------------------------------------
	除数不能为0
	永远执行:
	------------------------------------------------------------
	永远执行:
	Traceback (most recent call last):
	
	  File "E:\软件人\pkg02\数据分析.py", line 28, in <module>
	    x = 1/0
	
	ZeroDivisionError: division by zero
The @finally clause is mainly used to do some clean-up work, such as releasing external resources, (files or network connections), regardless of whether they make an error during use

Five, throw an exception

@ Use raise to throw exceptions: The python interpreter can automatically throw exceptions at runtime, and the program can use raise to throw exceptions in any code.
	try:
        score = float(input('输入分数:'))#强制类型转换
        if score < 0:
            raise ValueError("输入错误!!!")#抛出异常
    except ValueError as e:#捕获异常
        print(e)
    运行结果如下:
    输入分数:-1
	输入错误!!!

Six, custom exception

@Test the exception class defined by yourself
	class MyError(Exception):#继承Exception
        def __init__(self,value):
            self.value = value
            
    try:
        raise MyError("我自己定义的异常")
    except MyError as e:
        print(e)#打印出参数value的值
        
    运行结果如下:
	我自己定义的异常

Custom exceptions generally contain the following content:
1. Custom exception code
2. Custom exception question prompt
3. Customize the number of rows where the exception occurs

Seven, assertion

@Use assert (assert) to check a certain condition or result. Assertions are used to determine whether the value of an expression is True. If the assertion fails, the assert statement itself will throw an AssertionError. You can also use a comma followed by an expression after the assertion. If the assertion fails, the value of this expression is output.
When the @python interpreter executes a program, set the -o option to turn off the debugging mode and execute the program in optimized mode.
	try:
        assert(1+1 == 2)
        assert(1+1 == 3),'1+1 == 3不成立'
    except AssertionError as e:#捕获信息
        print(e)

    print("-"*60)
    
    assert(1+1 == 2)
    assert(1+1 == 3),'1+1 == 3不成立'
    运行结果如下:
   	1+1 == 3不成立#这是一开始用except捕获的结果
	------------------------------------------------------------
	Traceback (most recent call last):
	
	  File "E:\软件人\pkg02\数据分析.py", line 18, in <module>
	    assert(1+1 == 3),'1+1 == 3不成立'
	
	AssertionError: 1+1 == 3不成立

Summary: The exception module is often used in the program. Sometimes, we don’t know where the code may have an exception. If it is not caught, it may cause a certain loss, and the exception module reduces or even avoids these loss.

Guess you like

Origin blog.csdn.net/qq_45911278/article/details/111662037