一、异常处理
异常处理可以帮我们抓住程序中的导致崩溃的代码错误,保证程序能够继续征程运行,从而提升代码的健壮性。
while True:
try:
num1 = int(input("请输入一个数字1:"))
num2 = int(input("请输入一个数字2:"))
result = num1 / num2
except ValueError as e:各种异常类型存在的价值,可以针对异常进行专门的处理
print("请不要输入非数字", e)
except ZeroDivisionError as e:
print("除数不可以为0", e)
except Exception as e:虽然他可以抓住所有异常,但是我们不知道他是那种异常,无法针对处理 帮我们去抓住想象之外的错误可能。
print(e)
else: 可能出问题的代码没有发生异常时会执行的代码片段
print(result)
finally:
不管异常与否都会执行的代码片段,一般这里进行资源释放
Pass
二、自定义异常
Age200Error
AgeNegativeError
class AgeValueError(Exception):
def __init__(self, err_msg):
super().__init__(err_msg)
class Age200Error(Exception):
pass
class AgeNegativeError(Exception):
def __init__(self, err_msg):
super().__init__(err_msg)
class Human:
def __init__(self, name, age):
self.name = name
self.__age = age
def get_age(self):
return self.__age
def set_age(self, age):
if type(age) == int:
if 200 >= age >= 0:
self.__age = age
elif age > 200:
raise Age200Error("人类的年龄不能超过200岁")
else:
raise AgeNegativeError("年龄不能负数")
else:
raise AgeValueError("年龄只能是整数")
h = Human("lyh", 18)
h.set_age("aaaaaa")
三、异常的使用场景
1.保证程序的健壮性,即使出现了导致程序的崩溃的错误,只要主动抓捕的异常,仍旧可以保证程序正常运行
2.主动抛出抛出异常,结束当前的代码片段
import os
class FileFound(Exception):
pass
def search_file(path, file):
files = os.listdir(path)
for f in files: 遍历files
abs_f = path + os.sep + f
abs_f = os.path.join(path, f)
if os.path.isfile(abs_f) and f == file:如果是文件比对是否和file同名,如果是直接结束递归
raise FileFound(abs_f)
elif os.path.isdir(abs_f):如果是文件夹,递归(查找子文件夹中的所有文件)
search_file(abs_f, file)
try:
search_file("/Users/musicbear/imgtest_副本", "1111.jpeg")
except FileFound as e:
print(f"已找到目标:{e}")