文章目录
1 异常的定义
程序编写完成后,用户输入的数据不在定义范围内,打开文件结果格式不对,读取数据库可能数据库是空的,这些都会导致异常的发生,在程序里异常被称为‘exception’,如下代码就是一个典型的异常语句,运用了try…except 的方法。
from shutil import copyfile
try:
copyfile('F:/a.txt','G:/a.txt')
except BaseException as e:
print(e)
输出结果:
[Errno 2] No such file or directory: 'F:/b.txt'
2 try…except…结构处理异常
2.1 try 语句的语法结构
try…except…结构处理异常的基本语法为:
Try:
<被监控的可能发生异常的语句>
except BaseException as e:
<出错后输出的语句>
print(e)#该语句能够输出错误的类型,帮助用户快速找到问题所在
2.2 try语句的执行顺序
观察下面两段代码,可以发现try…except…结构的执行方式是只有当try中的语句报错了才会执行except中的语句。
try:
print('step1')
print(3/0)
print('step2')
except BaseException as e:
print(e)
print('step3')
print('step4')
输出结果:
step1
division by zero
step3
step4
try:
print('step1')
print(3/3)
print('step2')
except BaseException as e:
print(e)
print('step3')
print('step4')
输出结果:
step1
1.0
step2
step4
3 try …多个except…异常处理结构
有时候try中的语句可能有多种类型的异常,这就需要多个except结构来接收:
try:
a=input('请输入被除数:')
b=input('请输入除数:')
c=float(a)/float(b)
print(c)
except ZeroDivisionError:
print('除数不能为0')
except NameError:
print('请输入变量')
except TypeError :
print('请输入浮点数或整数的数字')
except BaseException as e:
print(e)
print('程序结束!')
4 try…except…else…finally
该结构的语法规则为如果try种的语句没有报错,则执行else种的语句,如果报错,则执行except中的语句,最后执行finally中的语句。
try:
a=input('请输入被除数:')
b=input('请输入除数:')
c=float(a)/float(b)
except ZeroDivisionError:
print('除数不能为0')
except NameError:
print('请输入变量')
except TypeError :
print('请输入浮点数或整数的数字')
except BaseException as e:
print(e)
else:
print(c)
finally:
print('恭喜,程序执行结束啦!')
输出结果:
请输入被除数:1
请输入除数:2
0.5
恭喜,程序执行结束啦!
或者:
请输入被除数:1
请输入除数:0
除数不能为0
恭喜,程序执行结束啦!
5 常见错误类型
6 使用traceback模块打印错误信息
使用traceback.print_exc()函数可以直接输出空值。
import traceback
try:
print(3/0)
except:
with open('F:a.txt','a') as f:
traceback.print_exc(file=f)
7 自定义异常类
有时编好的程序用户输入错误的时候,这是想要自定义错误类型,可以使用raise函数调用类的方法,从程序中可以看出,首先定义一个类,然后运用raise()函数调用这个类即可在用户输入错误的时候调用类抛出错误。
其中,if name==‘main’:的解释如下:
class A(Exception):
def __init__(self):
Exception.__init__(self)
def __str__(self):
return '年龄输入错误,请输入0-150之间的数字'
if __name__=='__main__':
age=int(input('请输入您的年龄:'))
if age<0 or age>150:
raise A()
else:
print('您的年龄为{}'.format(age))
输出结果:
请输入您的年龄:500
Traceback (most recent call last):
File "C:/Users/Administrator/Desktop/练习代码/测试代码05.py", line 348, in <module>
raise A()
__main__.A: 年龄输入错误,请输入0-150之间的数字