# 在python中异常的分析

>>> 1/0
traceback (most recent call last):
file “”, line 1, in
1/0
zeropisionerror: integer pision or modulo by zero

>>> def inputnum():
x=input(‘enter the first number: ‘)
y=input(‘enter the first number: ‘)
try:
print x/y
except zeropisionerror:
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 zeropisionerror:
if self.muffled:
print ‘pision 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
zeropisionerror: integer pision or modulo by zero
>>> c.muffled=true
>>> c.calc(‘1/0’)
pision by zero is illegal

try:
x=input(‘enter the first number:’)
y=input(‘enter the seconed number:’)
print x/y
except zeropisionerror:
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(zeropisionerror,typeerror,nameerror):

try:
x=input(‘enter the first number:’)
y=input(‘enter the seconed number:’)
print x/y
except(zeropisionerror,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…

Posted in 未分类