【Python基础教程】第8章 异常
来源:互联网 发布:卓尔集团待遇 知乎 编辑:程序博客网 时间:2024/05/19 03:18
1.自定义异常:继承Exception
#1.自定义异常类#方法:从Exception类继承class SomeCustomException(Exception):pass2.处理异常
#(1)捕捉异常:try/excepttry: x = input('Enter the first number:') y = input('Enter the second number:') print x/yexcept ZeroDivisionError: print "The second number couldm't be zero"#注:如果异常没有被捕捉,就会传递到函数调用的地方。# 如果一直没有被捕捉,会一直传到程序的最顶层。# 最终,在Trackback中打印输出。#(2)传递异常:raiseclass MuffledCalculator: muffled = False def calc(self, expr): try: return eval(expr) except ZeroDivisionError: if self.muffled: print 'Division by zero is illegal' else: raise#将异常传递#(3)多个异常#(3.1)except ZeroDivisionError:print "......"except TypeError:print "......"#(3.2)except (ZeroDivisionError, TypeError), e:print e#(4):捕捉全部异常:仅仅使用except(很危险,不提倡使用)try: x = input('Enter the first number:') y = input('Enter the second number:') print x/yexcept: print "Something wrong happened.."#(5)try/except 和 elsewhile True: try: x = input('Enter the first number:') y = input('Enter the second number:') value = x/y print 'x/y is', value except Exception, e: print "The input is invalid" print "Please try again" else: break#注:except语句和else语句仅仅会执行一个。# 当发生异常,不执行else;当没有反生异常,执行else#(5)finallytry: 1/0except NameError: print 'Unknown variable'else: print 'That went well'finally: print 'other things'
0 0
- Python基础教程之第8章 异常
- 【Python基础教程】第8章 异常
- <<Python基础教程>>学习笔记 | 第08章 | 异常
- 《Python基础教程》读书笔记(3)之第8章异常(关键词:Python/异常/try/except/finally)
- python基础教程第8章笔记
- 《Python基础教程》读书笔记-8 异常
- 【Python基础教程】第5章
- python基础教程第9章
- python 基础教程第21章
- python基础教程共60课-第36课异常处理
- Python基础教程——8 异常
- python基础教程----异常
- 《Python基础教程》第6~8章 学习笔记
- 《Python基础教程》第20章学习笔记
- Python基础教程之第1章 基础知识
- Python基础教程之第6章 抽象
- 【Python基础教程】第3章 字符串
- 【Python基础教程】第4章 字典
- CSS的继承特性
- HDU2255--奔小康赚大钱(KM算法)
- 【Python基础教程】第7章 类
- Android 用一个监听器实现多个监听
- CPU寻址范围(寻址空间)
- 【Python基础教程】第8章 异常
- Android 驱动开发
- OpenCV+kinect1.0手语识别(二)手部区域的抠图与跟踪
- SSL证书与Https应用部署小结
- 深入理解Direct3D9
- Android--闹钟小程序(Broadcast实现)
- linux如何显示一个文件的某几行
- Valid Parentheses
- 零基础学Python之一Python安装