个人自学成长记录
python 异常处理
上一篇 /
下一篇 2018-01-26 17:36:19
/ 个人分类:python
文件没有找到的异常:FileNotFoundError
try:
fileName=input("please input filename:")
open("%s.txt" %fileName)
except FileNotFoundError:
print("%s file not found" %fileName)
未声明或未初始化对象(没有属性):NameError
try:
print (stu)
except NameError:
print("stu not define!")
所有异常的基类:BaseException
try:
print (stu)
except BaseException:
print("stu not define!")
以上用try...except...处理,报错信息自定义
可以用try...except...as...将系统报错信息打印出来
try:
print (stu)
except BaseException as msg:
print(msg)
try...except...else...
else表示如果没有获取到异常,则执行某某
try...except...finally...
finally表示不论是否有异常都执行某某
raise抛出异常
try是执行过程中捕获异常,raise是通过事先定义一个条件,符合异常条件就抛出异常
注:raise后面只能接python标准异常类
def division(x,y):
if y==0:
raise ZeroDivisionError("Zero is not allow!")
return x/y
try:
division(8,0)
except BaseException as msg:
print(msg)
收藏
举报
TAG: