Goal
- The concept of exceptions
- Catching exceptions
- Delivery of exceptions
- Custom exceptions
01, the concept of the anomaly
- When the program runs, if
python 解释器
an error is encountered , the execution of the program is stopped, and some error messages are prompted, which is the exception
- The program stops executing and prompts for an error message , which we often call: throw (Raise) exception
Note program development, it is difficult to all the special circumstances are dealt with all-encompassing, through abnormal capture can be focused on emergencies to do a centralized treatment, so as to ensure the stability and robustness of the program
02, catching exception 2.1 simple catch exception syntax
- In program development, if execution of some code is not determined correctly , it can be added
try(尝试)
to catch the exception
- The simplest syntax format for catching exceptions:
try: 尝试执行的代码except: 出现错误的处理
try
try , write code below to try code, not sure if it will work properly
except
if not , write the code below to try to fail
Simple exception capture Walkthrough--to go to user input integer
try: # 提示用户输入数字 num = int(input("请输入数字:")) except: print("输入有误,请输入正确的数字") print("-" * 50) # 结果呈现 请输入数字:1 -------------------------------------------------- 请输入数字:a 输入有误,请输入正确的数字 --------------------------------------------------
2.2 Error Type snapping
- When the program executes, you may encounter different types of exceptions , and you need to respond differently to different types of exceptions , and you need to catch the type of error
- The syntax is as follows:
try: # 尝试执行的代码 passexcept 错误类型1: # 针对错误类型1,对应的代码处理 passexcept (错误类型2, 错误类型3): # 针对错误类型2 和 3 处理的代码 passexcept Exception as result: print("未知错误 %s" % result)
- When the
Python
interpreter throws an exception , the first word of the last line of error message is the type of error
Exception type capture walkthrough--requiring the user to enter an integer
Requirements
1, prompting the user to enter an integer
2, use 8
the integer divided by the user input and output
try: # 1,提示用户输入一个整数 num = int(input("输入一个整数:")) # 2,使用 ````8```` 除以用户输入的整数并且输出 result = 8 / num print(result) except ZeroDivisionError: print("除0错误") except ValueError: print("请输入正确的整数") # 结果呈现 输入一个整数:0 除0错误 输入一个整数:a 请输入正确的整数
Catch Unknown error
- In development, it is difficult to pre-contract all errors that may occur .
If you want the program to be terminated regardless of any errors , the python
interpreter throws an exception , you can add aexcept
The syntax is as follows:
except Exception as result: print("未知错误 %s" % result)
try: # 1,提示用户输入一个整数 num = int(input("输入一个整数:")) # 2,使用 ````8```` 除以用户输入的整数并且输出 result = 8 / num print(result) # except ZeroDivisionError: # print("除0错误") except ValueError: print("请输入正确的整数") except Exception as result: print("未知错误 %s " % result) # 结果呈现 输入一个整数:0
2.3 Exception capture Complete syntax
- In the actual development, in order to be able to handle complex anomalies, the complete exception syntax is as follows:
try: # 尝试执行的代码 passexcept 错误类型1: # 针对错误类型1,对应的代码处理 passexcept (错误类型2, 错误类型3): # 针对错误类型2 和 3 处理的代码 passexcept Exception as result: print("未知错误 %s" % result)else: # 没有异常才会执行的代码 passfinally: # 无论是否有异常,都会执行的代码 print("无论是否有异常,都会执行的代码")
else
Code that executes only if there is no exception
finally
Code that executes regardless of whether there is an exception
try: # 1,提示用户输入一个整数 num = int(input("输入一个整数:")) # 2,使用 ````8```` 除以用户输入的整数并且输出 result = 8 / num print(result) # except ZeroDivisionError: # print("除0错误") except ValueError: print("请输入正确的整数") except Exception as result: print("未知错误 %s " % result) else: print("尝试成功") finally: print("无论是否有异常,都会执行的代码") print("-" * 20) # 结果呈现 输入一个整数:q 请输入正确的整数 无论是否有异常,都会执行的代码 -------------------- 输入一个整数:0 未知错误 division by zero 无论是否有异常,都会执行的代码 -------------------- 输入一个整数:1 8.0 尝试成功 无论是否有异常,都会执行的代码 --------------------
03, Abnormal Delivery
- exception passing --When a function/method execution occurs , an exception is passed to the calling party of the function/method
- If passed to the main program , still no exception handling , the program will be terminated
Tips
- In development, you can increase the exception capture in the main function
- Other functions that are called in the main function are passed to the exception capture of the main function whenever an exception occurs.
- This does not require the addition of a large number of exception captures in the code to keep the code clean
Demand
1, the definition function demo1()
prompts the user to enter an integer and returns
2, defining function demo2()
callsdemo1()
3, called in the main programdemo2()
def demo1(): return int(input("请输入一个整数:")) def demo2(): return demo1() try: print(demo2()) except Exception as result: print("未知错误:%s" % result) # 结果呈现 请输入一个整数:q 未知错误:invalid literal for int() with base 10: ‘q‘
04, throw raise Exception 4.1 application scenario
- In development, in addition to code execution error , the
python
interpreter throws an exception
- You can also proactively throw exceptions based on your application-specific business requirements
Example
- Prompts the user for a password , if the length is less than 8, throws an exception
Attention
- The current function is only responsible for prompting the user to enter the password, if the password length is not correct, need other functions to do extra processing
- So you can throw exceptions , there are other functions that need to be handled to catch exceptions
4.2 Throwing Exceptions
python
An Exception
exception class is provided in the
- At development time, if you meet a specific business need , you want to throw an exception , you can:
- To create an
Exception
object
raise
throwing Exception objects with keywords
Demand
- Define
input_password
a function that prompts the user to enter a password
- Throws an exception if the user enters length < 8
- If the user enters a length of >= 8, the input password is returned
def input_password(): # 1,提示用户输入密码 pwd = input("请输入密码: ") # 2, 如果用户输入长度 >= 8 ,返回输入的密码 if len(pwd) >= 8: return pwd # 3, 如果用户输入长度 < 8 ,抛出异常 print("主动抛出异常") # 1> 创建异常对象 - 可以使用错误字符串作为参数 ex = Exception("密码长度不够") # 1> 主动抛出异常 raise ex try: print(input_password()) except Exception as result: print(result) # 结果呈现 请输入密码: 12345678 12345678 请输入密码: 123 主动抛出异常 密码长度不够
Python Object-Oriented---exceptions