每个异常都是一 些类的实例,这些实例可以被引发,并且可以用很多种方法进行捕捉,使得程序可以捉住错误并且对其进行处理
>>> 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 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 "<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多种异常类型
立即学习“Python免费学习笔记(深入)”;
企业在线记账管理系统是一款功能强大,特别简单易用的财务在线记账软件,它不需要用户了解深奥的财务知识,不用培训即会使用,特别适合中小企业,门店等用在日常经营管理中来管理现金流水账,应收应付帐,以及公司记账等相关财务活动。 环保时代企业在线记账管理系统也可以说是一款傻瓜型的流水账管理系统,通过记录每日现金支出,收入的明细账,为企业管理者提供详细的收入支出日报,月报,欠款明细等重要信息。是您进行企业管
773
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中异常的详细说明的详细内容,更多请关注php中文网其它相关文章!
python怎么学习?python怎么入门?python在哪学?python怎么学才快?不用担心,这里为大家提供了python速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号