首页 / PYTHON / 关于python中异常的详细说明
关于python中异常的详细说明
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了关于python中异常的详细说明,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2168字,纯文字阅读大概需要4分钟。
内容图文
![关于python中异常的详细说明](/upload/InfoBanner/zyjiaocheng/431/7c3c815664f94f98a024458f96f1d725.jpg)
>>> 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中异常的详细说明的详细内容,更多请关注Gxl网其它相关文章!
内容总结
以上是互联网集市为您收集整理的关于python中异常的详细说明全部内容,希望文章能够帮你解决关于python中异常的详细说明所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。