Python异常处理

Python 用异常对象(exception object)来表示异常情况。

1. 查看内建的异常类:
>>> import exceptions
>>> dir(exceptions)
所有这些异常都可以用在raise语句中:
>>> raise ArithmeticError

2. 创建自己的异常类:
就像其他类一样----只要确保从Exception类继承(不管是间接的或者是直接的,也就是
说继承其他的内建异常类也是可以的)。
例如:
class SomeCustomException(Exception): pass

3. 捕捉异常:
例如:

try:
x = input('Enter the first number: ')
y = input('Enter the second number: ')
print x/y
except ZeroDivisionError:
print "The second number can't be zero!"
except TypeError:
print "That wasn't a number, was it?"

例如:

try:
x = input('Enter the first number: ')
y = input('Enter the second number: ')
except (ZeroDivisionError, TypeError, NameError):
print 'You numbers were bogus...'


4. 捕捉对象:
例如:

try:
x = input('Enter the first number: ')
y = input('Enter the second number: ')
print x/y
except (ZeroDivisionError, TypeError), e:
print e


5. 真正的全捕捉:
例:

try:
x = input('Enter the first number: ')
y = input('Enter the second number: ')
print x/y
except:
print 'Something wrong happened...'


6. 万事大吉:
一些坏事发生时执行一段代码,例:

try:
print 'A simple task'
except:
print 'What? Something went wrong?'
else:
print 'Ah... It went as planned.'

例:

while True:
try:
x = input('Enter the first number: ')
y = input('Enter the second number: ')
value = x/y
print 'x/y is', value
except:
print 'Invalid input. Please try again.'
else:
break


7. 最后:
Finally子句,用来在可能的异常后进行清理,它和try子句联合使用:

x = None
try:
x = 1/0
finally:
print 'Cleaning up...'
del x
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值