首页 > 编程 > Python > 正文

详解在Python中处理异常的教程

2020-02-23 01:24:28
字体:
来源:转载
供稿:网友

什么是异常?

异常是一个事件,其中一个程序,破坏程序的指令的正常流的执行过程中而发生的。一般情况下,当一个Python脚本遇到一些情况不能处理,就抛出一个异常。异常是一个Python对象,它表示一个错误。

当Python脚本抛出一个异常,它必须处理异常,否则将立即终止。
处理异常:

如果有可能会引发异常的一些可疑的代码,就可以通过将可疑的代码在一个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语句可以有多个不同的语句。当try块中包含可能会引发不同类型的异常语句,这是很有用的。     也可以提供一个通用的except子句,它用来处理任何异常。     except子句后,可以包括其他子句。块没有引发异常:在别的块中的代码,如果在try中的代码执行。     在else块是不需要try:块的代码的保护。

例子

这里是简单的例子,这将打开一个文件并写入内容的文件中并移出正常:

#!/usr/bin/pythontry:  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()

这将产生以下结果:

Written content in the file successfully

示例:

这里有一个更简单的例子,它试图打开没有权限并在文件中写入内容,所以它会引发一个异常:

#!/usr/bin/pythontry:  fh = open("testfile", "r")  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"

这将产生以下结果:

Error: can't find file or read data

在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 语句捕获所有出现的异常。使用这种try-except 声明不被认为是一个良好的编程习惯,但因为它捕获所有异常,但不会使程序员找出可能出现的问题的根本原因。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表