在我们编写脚本或者进行软件开发过程中总会遇见很多的异常和错误,而Python里面有两个非常重要的功能,能够很好的处理异常和任何意外错误,这两个功能就是异常处理和断言。
异常处理:主要包含语法错误和其他的标准异常,标准异常介绍如下表。
断言:断言是一种理智检查,当程序的测试完成,你可以打开或关闭。断言的最简单的方法就是把它比作 raise-if 语句 (或者更准确,加 raise-if-not 声明). 一个表达式进行测试,如果结果出现 false,将引发异常。断言是由 assert 语句,在Python中新的关键字,在Python1.5版本中引入使用的关键字。
程序员常常放置断言来检查输入的有效,或在一个函数调用后检查有效的输出。
一、标准异常表
异常示例:
1、FileNotFoundError
尝试打开文d:\\openstack.txt文件由于文件不存在就会报出FIleNotFoundError:
f=open("d:\\openstack.txt")
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
f=open("d:\\openstack.txt")
FileNotFoundError: [Errno 2] No such file or directory: 'd:\\openstack.txt'
2、ZeroDivisionError
除法运算或取模运算中,除数为零的情况
>>> 5/0
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
5/0
ZeroDivisionError: division by zero
3、ImportError
一般是在导入模块时,由于模块不存在等原因导致报错
>>> import wwww
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
import wwww
ImportError: No module named 'wwww'
4、ValueError
一般是由于传入参数的数据类型错误引起报错。
>>> a="sterc"
>>> int(a)
Traceback (most recent call last):
File "<pyshell#4>", line 1, in <module>
int(a)
ValueError: invalid literal for int() with base 10: 'sterc'
>>>
二、异常处理
python中包含两种异常处理语句,可以使用try...except...finally或者try...except..else语句来处理异常,接下来简单的介绍两种语句的语法以及两者的区别:
try语句原理:
首先,执行try子句(在关键字try和关键字except之间的语句)
如果没有异常发生,忽略except子句,try子句执行后结束。
如果在执行try子句的过程中发生了异常,那么try子句余下的部分将被忽略。如果异常的类型和 except 之后的名称相符,那么对应的except子句将被执行。最后执行 try 语句之后的代码。
如果一个异常没有与任何的except匹配,那么这个异常将会传递给上层的try中。
一个 try 语句可能包含多个except子句,分别来处理不同的特定的异常。最多只有一个分支会被执行。
处理程序将只针对对应的try子句中的异常进行处理,而不是其他的 try 的处理程序中的异常。
一个except子句可以同时处理多个异常,这些异常将被放在一个括号里成为一个元组。
try...except..else语法:
try:
You do your operations here
......................
except ExceptionI:
If there is ExceptionI, then execute this block.
except ExceptionII:
If there is ExceptionII, then execute this block.
......................
else:
If there is no exception then execute this block.
单个 try 语句可以有多个except语句。 当 try 块包含可能抛出不同类型的异常声明这是有用的
也可以提供一个通用的 except 子句来处理异常(不提倡)
except子句后,可以包括 else 子句。 如果代码在try:块不引发异常则代码在 else 块执行
else是可以正常运行部存在异常的代码,这不需要 try: 块的保护
try:
fh = open("testfile", "w+")
fh.write("This is my test file for exception handling!!")
except IOError:
print ("Error: can\'t find file or read data")
else:
print ("Written content in the file successfully")
fh.close()
正常执行后就会生成testfile文件里面的内容为:This is my test file for exception handling!
而控制台输出结果如下:
Written content in the file successfully
用except子句处理多个异常
刚才我们的示例是处理了一个类型的异常,而except可以处理多个类型的异常例如
except(ValueError,ImportError,RuntimeError)这是可以将多个类型的标准错误写成一个元组,但是做个类型容易造成我们队类型的报错分析难度大。
try:
fh = open("testfile", "r")
fh.write("This is my test file for exception handling!!")
except (ValueError,ImportError,RuntimeError):
print ("Error: can\'t find file or read data&