异常处理是指程序在出现问题时,依然可以正确的执行剩余的程序,而不会因为异常而中指程序执行。
python 中所有异常的父类:BaseException
异常基本结构
try:
代码
except BaseException [as e]:
异常处理
try:
print("step1")
a = 3 / 0 # 抛出异常进入 except
print("step2")
except Exception as ex:
print("step3")
print(ex)
print("step4")
返回值:
step1
step3
division by zero
step4
多个except结构
按照先子类后父类的顺序捕获多个异常
try:
代码
except Exception1:
异常处理
except Exception2:
异常处理
try:
a = input("请输入一个被除数:")
b = input("请输入一个除数:")
c = float(a) / float(b)
print(c)
except ZeroDivisionError:
print("除数不能为0")
except ValueError:
print("输入值不是规范数字")
except BaseException:
print("其他异常")
try… except…else 结构
如果try 中没有抛出一成,则执行else 块,如果抛出了异常,则执行except块,不执行else
try:
a = input("请输入一个被除数:")
b = input("请输入一个除数:")
c = float(a) / float(b)
print(c)
except ZeroDivisionError:
print("除数不能为0")
except ValueError:
print("输入值不是规范数字")
except BaseException:
print("其他异常")
else:
print("结果为:",c)
try…except…else 结构
无论是否发生异常,finally块都会被执行,通常用来释放try 中申请的资源
try:
a = input("请输入一个被除数:")
b = input("请输入一个除数:")
c = float(a) / float(b)
print(c)
except ZeroDivisionError:
print("除数不能为0")
except ValueError:
print("输入值不是规范数字")
except BaseException:
print("其他异常")
else:
print("结果为:", c)
finally:
print("finally")
return
两个作用:1 结束方法运行,2 返回值 ;
一般不把return 放到异常处理结构中,而是放到方法最后
常见异常汇总说明
1 SyntaxError:语法错误
2 NameError:尝试访问一个没有声明的变量
3 ZeroDivisionError :除数为0错误
4 ValueError :数值错误
5 TypeError:类型错误
6 AttributeError: 访问对象不存在的属性
7 indexError 索引越界异常
8 keyError 字典的关键字不存在
with 上下文管理
通过with上下文管理,更方便的实现释放资源的操作
结构如下:
with context_expr[as var]:
语句块
with open("d:/abc.txt") as f:
for line in f:
print(line)
执行完,文件对象被关闭
traceback
打印异常信息
import traceback
try:
print("step1")
a = 3 / 0 # 抛出异常进入 except
print("step2")
except:
traceback.print_exc()
print("step4")
try:
print("step1")
a = 3 / 0 # 抛出异常进入 except
print("step2")
except:
# 将日常信息输出到文件中
with open("d:/a.txt","a") as f:
traceback.print_exc(file=f)
print("step4")
自定义异常类
通常继承Exception或者其子类即可,命名一般以Error Exception结尾
class AgeError(Exception):
def __init__(self, errorInfo):
Exception.__init__(self)
self.errorInfo = errorInfo
def __str__(self):
return "年龄错误"
##测试代码
if __name__ == "__main__": # 如果为true,则模块是作为独立文件运行,可以执行测试代码
age = int(input("age="))
if age < 1 or age > 150:
raise AgeError(age)
else:
print("age=", age)