python notes: exceptions and exception handling

1. The concept of exception:

• When the program is running, if the Python interpreter encounters an error, it will stop the execution of the program and prompt some error messages. This is an exception. • The action of the program stopping execution
and prompting an error message is usually called: throwing (raise)Exception

When developing a program, it is difficult to handle all special situations in an all-round way. Exception capture can focus on handling emergencies to ensure the stability and robustness of the program.

2. Catching exceptions

2.1 Simple syntax for catching exceptions
• In program development, if the execution of some code is not sure whether it is correct, you can add try (try) to catch exceptions
• The simplest syntax format for catching exceptions:

try:
	尝试执行的代码《不确定是否能正常执行》
except:
	编写尝试失败的代码《即以上代码不能正常执行》

Regardless of whether there is an exception or not, the code will be executed later

Simple exception catching drill - asking the user to enter an integer

try:
	num = int(input("请输入数字:")) # 提示用户输入一个数字
except:
	print("请输入正确的数字")

2.2 Error type capture

• When the program is executed, different types of exceptions may be encountered, and different responses need to be made for different types of exceptions. At this time, it is necessary to capture the error type • The syntax is as follows
:

try:
# 尝试执行的代码 pass 
except 错误类型1:
	# 针对错误类型1,对应的代码处理
except (错误类型2, 错误类型3):
	# 针对错误类型2和3,对应的代码处理
except Exception as result:
	print("未知错误 %s" % result)

When the Python interpreter throws an exception, the first word of the last line of the error message is the error type

Exception type catching walkthrough - asking the user to enter an integer

Requirements:
1. Prompt the user to enter an integer
2. Divide the integer entered by the user by 8 and output

try:
	num = int(input("请输入整数:")) 
	result = 8 / num
	print(result) 
except ValueError: #错误类型1
	print("请输入正确的整数") 
except ZeroDivisionError: #错误类型2
	print("除 0 错误")

2.3 Catching unknown errors
• During development, it is still difficult to predict all possible errors •
If you want the program to not be terminated because the Python interpreter throws an exception regardless of any errors, you can add more an except

The syntax is as follows:

except Exception as result:
	print("未知错误 %s" % result)

2.4 Complete syntax for exception capture
• In actual development, in order to be able to handle complex exception situations, the complete exception syntax is as follows:

try:
	# 尝试执行的代码 
except 错误类型1:
	# 针对错误类型1,对应的代码处理
except 错误类型2:
	# 针对错误类型2,对应的代码处理  
except (错误类型3, 错误类型4):
	# 针对错误类型3和4,对应的代码处理
except Exception as result:
	# 打印错误信息 print(result) 
else:
	# 没有异常才会执行的代码 pass 
finally:
	# 无论是否有异常,都会执行的代码 
	print("无论是否有异常,都会执行的代码")

The complete exception catching code from a previous walkthrough is as follows:

try:
	num = int(input("请输入整数:")) 
	result = 8 / num
	print(result) 
except ValueError:
	print("请输入正确的整数") 
except ZeroDivisionError:
	print("除 0 错误") 
except Exception as result:
	print("未知错误 %s" % result) 
else:
	print("正常执行") 
finally:
	print("执行完成,但是不保证正确")

case1:
Please enter an integer: 8
1.0
Normal execution
The execution is completed, but it is not guaranteed to be correct.
Case2:
Please enter an integer: 0.2
Please enter a correct integer.
The execution is completed, but it is not guaranteed to be correct.

3. Exception delivery

• Exception delivery - When an exception occurs during function/method execution, the exception will be passed to the caller of the function/method. •
If it is passed to the main program and there is still no exception handling, the program will be terminated.

Tips:
• During development, you can add exception catching in the main function.
• As long as an exception occurs in other functions called in the main function, it will be passed to the exception catching of the main function.
• This way there is no need to add a lot of exceptions to the code. Exception capture can ensure the cleanliness of the code

Requirements
1. Define the function demo1() to prompt the user to enter an integer and return it
2. Define the function demo2() to call demo1()
3. Call demo2() in the main program

def demo1():
	return int(input("请输入一个整数:"))

def demo2():
	return demo1()

try:
	print(demo2()) 
except ValueError:
	print("请输入正确的整数") 
except Exception as result:
	print("未知错误 %s" % result)

4. Throw raise exception

• During development, in addition to the Python interpreter throwing exceptions when code execution errors occur, exceptions can also be actively thrown according to the unique business needs of the application •
Python provides an Exception exception class [you can also define your own exception class]
• During development, if you want to throw an exception to meet specific business needs, you can:
1. Create an Exception object
2. Use the raise keyword to throw the exception object

try:
	print("请输入登录账号: ")
	username = input(">> ")
	if username != "zhangsan":
		raise Exception("用户名输入错误")
	print("请输入登录密码: ")
	password = input(">>: ")
	if (password != "123456"):
		raise Exception("密码输入错误")
except Exception as e:
	print(e)

Using the raise statement to actively throw exceptions means that developers can create program exceptions by themselves. The program exception here does not refer to system exceptions such as memory overflow and list out-of-bounds access, but refers to the occurrence of user errors during the execution of the program. Input data does not match the required data, user operation errors, etc. **These problems require the program to handle them and give corresponding prompts.

assert assertion:
The assert statement, also known as the assertion statement, can be regarded as a reduced version of the if statement. It is used to determine the value of a certain expression. If the value is true, the program can continue to execute; otherwise, Python explains The processor will report an AssertionError error.

The syntax structure of the assert statement is:

assert expression[, parameters]

When the expression is true, the program continues to execute;
when the expression is false, an AssertionError is thrown and the parameters are output.

The execution flow of the assert statement can be represented by an if judgment statement, as shown below:

 if 表达式==True:
    程序继续执行
else:
    程序报 AssertionError:参数 
def foo(s):
    n = int(s)
    assert n != 0, 'n is zero!'
    return 10 / n

foo('0')

# 代码执行结果
AssertionError: n is zero!

Guess you like

Origin blog.csdn.net/qq_44804542/article/details/115996266