Python基础--学习笔记1
来源:互联网 发布:百度地图js api 编辑:程序博客网 时间:2024/05/21 09:02
第八章:异常
1、
注:这里的循环只在没有异常引发的情况下才会退出,而且使用expect Exception,打印更加有用的信息
while 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 'Invalid input:',e print 'Please try again' else: break
<span style="color:#ff0000;">Enter the first number: 12Enter the second number: 0Invalid input: integer division or modulo by zeroPlease try againEnter the first number: 12Enter the second number:'hello'Invalid input: unsupported operand type(s) for /: 'int' and 'str'Please try againEnter the first number: kdInvalid input: name 'kd' is not definedPlease try againEnter the first number: 12Enter the second number: Invalid input: unexpected EOF while parsing (<string>, line 0)Please try againEnter the first number: 12Enter the second number: 3x/y is 4</span>
2、Finally子句
它用来在可能的异常后进行清理。它和try子句联合使用:
try: x = 1/0finally: #发生异常后进行清理 print 'Cleaning up...' del x
上面的代码中,finally子句肯定会被执行,不管try子句中是否发生异常(在try子句之前初始化x的原因是如果不这样做,由于ZeroDivisionError的存在,x就永远不会被赋值。这样就会导致在finally子句中使用del删除它的时候产生异常,而且这个异常是无法捕捉的)。
运行这段代码,在程序崩溃之前,对于变量x的清理就完成了:
Cleaning up...Traceback (most recent call last): File "<pyshell#209>", line 2, in <module> x = 1/0ZeroDivisionError: integer division or modulo by zero
另外,还可以在同一个语句中组合使用try、except、finally和else(或其中3个)
try:1/0except NameError:print 'Unknow variable'else:print "That went well"finally:print "Cleaning up."Cleaning up.Traceback (most recent call last): File "<pyshell#229>", line 2, in <module> 1/0ZeroDivisionError: integer division or modulo by zero
try:12/9except NameError:print 'Unknow variable'else:print "That went well"finally:print "Cleaning up."1That went wellCleaning up.
- Python基础--学习笔记1
- python 基础学习笔记1
- Python 基础学习笔记1
- Python学习笔记1:Python基础
- Python基础学习笔记
- python基础学习笔记
- Python基础学习笔记
- python基础学习笔记
- python基础学习笔记
- python基础学习笔记
- 【Python学习笔记】基础
- Python学习笔记-基础
- Python 基础学习笔记
- Python基础学习笔记
- Python学习笔记(基础)
- Python学习笔记(基础)
- Python基础学习笔记
- Python基础学习笔记
- 【那些年我们用过的C#系列讲座 1】命名空间和我们第一个C#程序
- DivCSS+JavaScript实现 始终居中的半透明弹出层
- 选路技术
- 不同层面上操控I2C进行读写操作
- 用代码安装APK程序
- Python基础--学习笔记1
- CIPADDRESSCTRL 获取本机IP
- 如何生成密钥文件Snk .
- BIOS中英文对照表
- PetShop中.snk文件和AssemblyInfo.cs文件的作用 .
- DM6446开发攻略:V4L2视频驱动和应用分析
- imx25内核启动总结
- delphi与变长参数——可变类型开放数组(3)
- python - __str__ 和 __repr__