The exception of basic knowledge of Python (5)

abnormal

aims

  • Abnormal concept
  • Catch exception
  • Abnormal delivery
  • Throw an exception

01. 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 stopping the execution of the program and prompting an error message, we usually call it: raise an exception

When developing a program, it is difficult to deal with all special situations. Through exception capture, it is possible to deal with emergencies in a centralized manner, thereby ensuring the stability and robustness of the program.

02. Catch exceptions

2.1 Simple syntax for catching exceptions

  • In program development, if you are not sure whether the execution of some code is correct, you can add try (attempt) to catch the exception
  • The simplest syntax format for catching exceptions:
try:
   尝试执行的代码
except:
   出现错误的处理
  • try try, write the code to try below, not sure whether it can be executed normally
  • except if not, write the failed code below

Simple exception capture walkthrough-requiring 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 types of exceptions need to be responded to. At this time, it is necessary to capture the type of error
  • The syntax is as follows:
try:
   # 尝试执行的代码
   pass
except 错误类型1:
   # 针对错误类型1,对应的代码处理
   pass
except (错误类型2, 错误类型3):
   # 针对错误类型2 和 3,对应的代码处理
   pass
except Exception as result:
   print("未知错误 %s" % result)
  • When the Python interpreter throws an exception, the first word in the last line of the error message is the error type

Exception type capture walkthrough-requiring the user to enter an integer

demand

Prompt the user to enter an integer.
Divide 8 by the integer entered by the user and output

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


Capture unknown error

  • During development, it is necessary to predict all possible errors, and it is still difficult.
    If you want the program to not be terminated because the Python interpreter throws an exception, you can add an except
  • The syntax is as follows:
except Exception as result:
   print("未知错误 %s" % result)

2.3 The complete syntax of exception capture

  • In actual development, in order to be able to handle complex exceptions, the complete exception syntax is as follows:

prompt:

  • The application scenarios of the complete grammar will be better understood in the follow-up study, combined with actual cases
  • Now you can first have an impression of this grammatical structure
try:
   # 尝试执行的代码
   pass
except 错误类型1:
   # 针对错误类型1,对应的代码处理
   pass
except 错误类型2:
   # 针对错误类型2,对应的代码处理
   pass
except (错误类型3, 错误类型4):
   # 针对错误类型3 和 4,对应的代码处理
   pass
except Exception as result:
   # 打印错误信息
   print(result)
else:
   # 没有异常才会执行的代码
   pass
finally:
   # 无论是否有异常,都会执行的代码
   print("无论是否有异常,都会执行的代码")
  • else code that will be executed only when there is no exception
    f* inally code that will be executed regardless of whether there is an exception

The code to completely catch the exception 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("执行完成,但是不保证正确")

03. Abnormal delivery

  • Transmission of exceptions-when an exception occurs in the execution of a function/method, the exception will be passed to the calling party of the function/method
  • If it is passed to the main program and there is still no exception handling, the program will be terminated

prompt

  • In development, you can add exception capture in the main function
  • Other functions called in the main function, as long as there is an exception, will be passed to the exception capture of the main function
  • In this way, there is no need to add a large number of exception captures in the code, which can ensure the cleanliness of the code

demand

  • Define the function demo1() to prompt the user to enter an integer and return
  • Define function demo2() to call demo1()
  • 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)

04. Raise exception

4.1 Application scenarios

  • In development, except for code execution errors, the Python interpreter will throw exceptions
  • It can also actively throw exceptions according to the specific business needs of the application

Example

Prompt the user to enter the password, if the length is less than 8, throw an exception
Insert picture description here

note

  • The current function is only responsible for prompting the user to enter the password. If the password length is incorrect, other functions are required for additional processing

  • Therefore, an exception can be thrown, and the exception can be caught by other functions that need to be handled

4.2 Throw an exception

  • Python provides an Exception exception class
  • During development, if you want to throw an exception when meeting specific business requirements, you can:
    Create an Exception object
    Use the raise keyword to throw an exception object

demand

  • Define the input_password function to prompt the user to enter the password
  • If the user input length <8, throw an exception
  • If the user input length>=8, return the input password
def input_password():# 1. 提示用户输入密码
   pwd = input("请输入密码:")# 2. 判断密码长度,如果长度 >= 8,返回用户输入的密码
   if len(pwd) >= 8:
       return pwd
​
   # 3. 密码长度不够,需要抛出异常
   # 1> 创建异常对象 - 使用异常的错误信息字符串作为参数
   ex = Exception("密码长度不够")# 2> 抛出异常对象
   raise ex
​
​
try:
   user_pwd = input_password()
   print(user_pwd)
except Exception as result:
   print("发现错误:%s" % result)

Guess you like

Origin blog.csdn.net/weixin_42272869/article/details/113696313