异常处理结构
捕获一种异常
try:
try块
except Exception [as e]:
except 块
try:
try块
except Exception [as e]:
except 块
finally: //不管有没有异常都执行
try:
try块
except BaseException[as e]: //可以捕获所有异常(不精准)
except 块
例:
while True:
x = input('please input an Integer:')
try:
x = int(x)
print('you have input {0}'.format(x))
break
except Exception as e:
print('Input error.')
或者
while True:
x = input('please input an Integer:')
try:
x = int(x)
except Exception as e:
print('Input error.')
else: //没有异常执行
print('you have input {0}'.format(x))
break
捕获多种不同的异常
try:
try块
except Exception1 [as e]:
except 块1
except Exception2 [as e]:
except 块2
......
例
try:
x = input('请输入被除数:')
y = input('请输入除数:')
z = float(x) / float(y)
except ZeroDivisionError:
print('除数不能为0.')
except TypeError:
print('输入应为数值型')
except NameError:
print('变量不存在')
else:
print(x , '/', y, '=', z)
try:
x = input('input x:')
y = input('input y:')
result = float(x) / float(y)
except ZeroDivisionError:
print('divide by zero!')
except TypeError:
print('x,y 必须为数值型!')
else:
print('result = ', result)
finally:
print('executing finally clause')
程序调试:
①IDLE里面:debug -> debugger
②程序里面导入pdb模块:命令行中输入python -m pdb 程序名