Python标准异常和异常处理详解

2019-10-05 09:43:46于丽

except IOError:
   print "Error: can't find file or read data"
else:
   print "Written content in the file successfully"

以上程序输出结果:

Error: can't find file or read data

使用except而不带任何异常类型

你可以不带任何异常类型使用except,如下实例:

try:
   You do your operations here;
   ......................
except:
   If there is any exception, then execute this block.
   ......................
else:
   If there is no exception then execute this block.

以上方式try-except语句捕获所有发生的异常。但这不是一个很好的方式,我们不能通过该程序识别出具体的异常信息。因为它捕获所有的异常。

使用except而带多种异常类型
你也可以使用相同的except语句来处理多个异常信息,如下所示:

try:
   You do your operations here;
   ......................
except(Exception1[, Exception2[,...ExceptionN]]]):
   If there is any exception from the given exception list,
   then execute this block.
   ......................
else:
   If there is no exception then execute this block. 

try-finally 语句

try-finally 语句无论是否发生异常都将执行最后的代码。

try:
<语句>
finally:
<语句>    #退出try时总会执行
raise

注意:你可以使用except语句或者finally语句,但是两者不能同时使用。else语句也不能与finally语句同时使用

实例

#!/usr/bin/python

try:
   fh = open("testfile", "w")
   fh.write("This is my test file for exception handling!!")
finally:
   print "Error: can't find file or read data"

如果打开的文件没有可写权限,输出如下所示:

Error: can't find file or read data

同样的例子也可以写成如下方式:

#!/usr/bin/python

try:
   fh = open("testfile", "w")
   try:
      fh.write("This is my test file for exception handling!!")
   finally:
      print "Going to close the file"
      fh.close()
except IOError:
   print "Error: can't find file or read data"

当在try块中抛出一个异常,立即执行finally块代码。

finally块中的所有语句执行后,异常被再次提出,并执行except块代码。

参数的内容不同于异常。

异常的参数