Python 异常处理
如果你有一些可能引发异常的可疑代码,你可以通过将可疑代码放在一个 try 块中来保护你的程序。在 try 块之后,包括一个 except 语句,后面跟着一段处理问题的代码,尽可能优雅地处理。
- try 块包含可能引发异常的语句
 - 
如果发生异常,程序跳转到 except 块。
 - 
如果 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()
它将产生以下 输出 –
Written content in the file successfully
然而,将open()函数中的mode参数更改为”w”。如果测试文件尚不存在,程序在except块中遇到IOError,并打印以下错误消息−
Error: can't find file or read data
极客教程