Python 3语法小记(九) 异常 Exception
来源:互联网 发布:linux 文件后面带星号 编辑:程序博客网 时间:2024/04/30 04:00
常见异常:
Exception 所有异常的基类
AttributeError 特性应用或赋值失败时引发
IOError 试图打开不存在的文件时引发
IndexError 在使用序列中不存在的索引时引发
KeyError 在使用映射不存在的键时引发
NameError 在找不到名字(变量)时引发
SyntaxError 在代码为错误形式时引发
TypeError 在内建操作或者函数应用于错误类型的对象是引发
ValueError 在内建操作或者函数应用于正确类型的对象,但是该对象使用不合适的值时引发
ZeroDivisionError 在除法或者摸除操作的第二个参数为0时引发
自定义异常:
继承于 Exception 的类
class myException(Exception):pass
抛出异常:
raise 语句
>>> def division(x,y):if y == 0 :raise ZeroDivisionError('The zero is not allow')return x/y>>> try:division(1,0)except ZeroDivisionError as e:print(e)The zero is not allow
捕捉异常:
可同时捕捉多个异常,可捕捉异常对象,可忽略异常类型以捕捉所有异常
>>> try:x = int(input('input x:'))y = int(input('input y:'))print('x/y = ',x/y)except ZeroDivisionError: #捕捉除0异常print("ZeroDivision")except (TypeError,ValueError) as e: #捕捉多个异常,并将异常对象输出print(e)except: #捕捉其余类型异常print("it's still wrong")input x:12input y:0ZeroDivision>>> try:x = int(input('input x:'))y = int(input('input y:'))print('x/y = ',x/y)except ZeroDivisionError: #捕捉除0异常print("ZeroDivision")except (TypeError,ValueError) as e: #捕捉多个异常,并将异常对象输出print(e)except: #捕捉其余类型异常print("it's still wrong")input x:12input y:yinvalid literal for int() with base 10: 'y'
try/except 可以加上 else 语句,实现在没有异常时执行什么
>>> try:x = int(input('input x:'))y = int(input('input y:'))print('x/y = ',x/y)except ZeroDivisionError: #捕捉除0异常print("ZeroDivision")except (TypeError,ValueError) as e: #捕捉多个异常print(e)except: #捕捉其余类型异常print("it's still wrong")else: #没有异常时执行print('it work well')input x:12input y:3x/y = 4.0it work well
finally 语句
不管是否出现异常,最后都会执行finally的语句块内容,用于清理工作
所以,你可以在 finally 语句中关闭文件,这样就确保了文件能正常关闭
>>> try:x = int(input('input x:'))y = int(input('input y:'))print('x/y = ',x/y)except ZeroDivisionError: #捕捉除0异常print("ZeroDivision")except (TypeError,ValueError) as e: #捕捉多个异常print(e)except: #捕捉其余类型异常print("it's still wrong")else: #没有异常时执行print('it work well')finally: #不管是否有异常都会执行print("Cleaning up")input x:12input y:3x/y = 4.0it work wellCleaning up
异常抛出之后,如果没有被接收,那么程序会抛给它的上一层,比如函数调用的地方,要是还是没有接收,那继续抛出,如果程序最后都没有处理这个异常,那它就丢给操作系统了 -- 你的程序崩溃了,这点和C++一样的。
- Python 3语法小记(九) 异常 Exception
- Python 3语法小记(九) 异常 Exception
- Python 3语法小记(九) 异常 Exception
- Python 异常(Exception)
- Python 异常(Exception)
- Python 3语法小记(五)字符串
- Python 3语法小记(七)函数
- Python中的异常(Exception)
- Python 3语法小记(二)列表 和 元组
- Python 3语法小记(三) 集合set
- Python 3语法小记(四)字典 dictionary
- Python 3语法小记(八)类class
- Python 3语法小记 类class
- python 语法小记
- Python中获取异常(Exception)信息
- Python中获取异常(Exception)信息
- python的异常Exception
- python Exception 异常处理
- 嵌入式Linux
- 【摄影测量】4D的简单介绍
- HDU4565 So Easy!
- HDU 1010 Tempter of the bond
- HDU 1495 非常可乐(bfs)|POJ 3414 Pots(bfs+打印路径)
- Python 3语法小记(九) 异常 Exception
- hdu 4612 Warm up
- TOP PS aux时显示出来的栏目代表什么意思?比如:RSS、VSZ、STAT等
- poj 2528 Mayor's posters
- javascript如何解析特殊类型的json数据?
- Python文件读写时的换行符与回车符
- uva 586 Instant Complexity
- Android下利用spydroid+dss 实现多看一视频监控
- 杭电oj2003