python基础知识学习(异常处理结构)

异常处理结构

捕获一种异常

try:
	tryexcept Exception [as e]:
	except
try:
	tryexcept Exception [as e]:
	exceptfinally: //不管有没有异常都执行
try:
	tryexcept 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:
	tryexcept Exception1 [as e]:
	except1
except Exception2 [as e]:
	except2
	......

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 程序名

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值