每个异常都是一 些类的实例,这些实例可以被引发,并且可以用很多种方法进行捕捉,使得程序可以捉住错误并且对其进行处理
>>> 1/0 Traceback (most recent call last): File "", line 1, in 1/0 ZeroDivisionError: integer division or modulo by zero
异常处理
捕捉异常可以使用try/except语句。
>>> def inputnum():
x=input('Enter the first number: ')
y=input('Enter the first number: ')
try:
print x/y
except ZeroDivisionError:
print "The second number can't be zero"
>>> inputnum()
Enter the first number: 10
Enter the first number: 0
The second number can't be zeroraise 触发异常
>>> class Muff:
muffled=False
def calc(self,expr):
try:
return eval(expr)
except ZeroDivisionError:
if self.muffled:
print 'Division by zero is illegal'
else:
raise
>>> c=Muff()
>>> c.calc(10/2)
Traceback (most recent call last):
File "", line 1, in
c.calc(10/2)
File "", line 5, in calc
return eval(expr)
TypeError: eval() arg 1 must be a string or code object
>>> c.calc('10/2')
>>> c.calc('1/0')
Traceback (most recent call last):
File "", line 1, in
c.calc('1/0')
File "", line 5, in calc
return eval(expr)
File "", line 1, in
ZeroDivisionError: integer division or modulo by zero
>>> c.muffled=True
>>> c.calc('1/0')
Division by zero is illegal 多种异常类型
立即学习“Python免费学习笔记(深入)”;
用 php + mysql 驱动的在线商城系统,我们的目标为中国的中小企业及个人提供最简洁,最安全,最高效的在线商城解决方案,使用了自建的会员积分折扣功能,不同的会员组有不同的折扣,让您的商店吸引更多的后续客户。 系统自动加分处理功能,自动处理会员等级,免去人工处理的工作量,让您的商店运作起来更方便省事 采用了自建的直接模板技术,免去了模板解析时间,提高了代码利用效率 独立开发的购物车系统,使用最
try:
x=input('Enter the first number:')
y=input('Enter the seconed 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 seconed number:')
print x/y
except(ZeroDivisionError,TypeError,NameError):
print 'Your numbers were bogus...'捕捉对象
try:
x=input('Enter the first number:')
y=input('Enter the seconed number:')
print x/y
except(ZeroDivisionError,TypeError),e:
print e
Enter the first number:1
Enter the seconed number:0
integer division or modulo by zero捕捉所有异常
try:
x=input('Enter the first number:')
y=input('Enter the seconed number:')
print x/y
except:
print 'something wrong happened...'
Enter the first number:
something wrong happened...更多在python中异常的分析相关文章请关注PHP中文网!










