异常
查看异常类
import exceptions
dir(exceptions)
引发异常
raise Exception
raise Exception("Oh, some problem")
捕获异常
except捕获异常
try:
x = input()
y = input()
print x/y
except ZeroDivisionError:
print "the 2nd number can not be 0"
在except中不指定异常类,所有异常都会被捕获
try:
x = input()
y = input()
print x/y
except :
print "the 2nd number can not be 0"
跟前一个的区别是,前一个只捕获除0异常,后者还可以捕获类型错误等等.
给except提供两个参数
打印异常信息:
try:
...
except Exception, e:
...
访问异常对象本身
try:
x = input()
y = input()
print x/y
except (ZeroDivisionError, typeError), e:
# 在3.0版本中 except (ZeroDivisionError, typeError) as e:
print e
重新引发异常
#!/usr/bin/env python
class MuffledCalculator:
muffled = False
def calc(self, expr):
try:
return eval(expr)
except ZeroDivisionError:
if self.muffled:
print 'Division by zero is illegal!' # 异常处理到此终止
else:
raise # 异常传递
calculator = MuffledCalculator()
print calculator.calc('10/2')
print calculator.calc('10/0')
self.muffled = True
print calculator.calc('10/0')
else子句,没有引发异常,执行该子句
while True:
try:
x = input()
y = input()
print x/y
except Exception,e:
print e
print "try again"
else:
break