关于python中异常的详细说明

每个异常都是一 些类的实例,这些实例可以被引发,并且可以用很多种方法进行捕捉,使得程序可以捉住错误并且对其进行处理

>>> 1/0
traceback (most recent call last):
file “”, line 1, in
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 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):
print ‘your numbers were bogus…’

捕捉对象

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…

以上就是关于python中异常的详细说明的详细内容,更多请关注 第一php社区 其它相关文章!

Posted in 未分类

发表评论