每个异常都是一 些类的实例,这些实例可以被引发,并且可以用很多种方法进行捕捉,使得程序可以捉住错误并且对其进行处理
>>> 1/0
traceback (most recent call last):
file "<pyshell#0>", line 1, in <module>
1/0
zeropisionerror: integer pision 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 zero
raise 触发异常
>>> 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 "<pyshell#33>", line 1, in <module>
c.calc(10/2)
file "<pyshell#31>", 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 "<pyshell#35>", line 1, in <module>
c.calc('1/0')
file "<pyshell#31>", line 5, in calc
return eval(expr)
file "<string>", line 1, in <module>
zerodivisionerror: integer pision or modulo by zero
>>> c.muffled=true
>>> c.calc('1/0')
division by zero is illegal
多种异常类型
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 pision 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中异常的详细说明的详细内容。