首页 > 代码库 > 理解Python语言里的异常(Exception)

理解Python语言里的异常(Exception)

Exception is as a sort of structured "super go to".
异常是一种结构化的"超级goto".

作为一个数十年如一日地钟爱C语言的程序员(因为C程序员需要记忆的关键字很少,而且可以很惬意地玩内存),对于高级语言如Python里的异常(Exception)一直不甚理解,尤其是其实现机理。但读了《Learning Python》一书中上面这句话(尤其是goto关键字)后,忽然豁然开朗。

如果用C语言编写一个鲁棒性良好的程序,一般得在每一个可能出错的运算之后检查返回值或状态码,然后在程序执行的时候根据返回值或状态做出不同的处理。例如:

 1 int doStuff()
 2 {                                       /* C program                */
 3         if (doFirstThing() == ERROR)    /* Detect errors everywhere */
 4                 return ERROR;           /* even if not handled here */
 5         if (doNextThing() == ERROR)
 6                 return ERROR;
 7         ...
 8         return doLastThing();
 9 }
10 
11 int main()
12 {
13         if (doStuff() == ERROR)
14                 badEnding();
15         else
16                 goodEnding();
17         ...
18 }

实际上,在现实的C程序中,通常用于处理错误检查和用于实际工作的代码数量相当。 但是, 在Python中,程序员就不用那么小心翼翼和神经质了。你可以把程序的任意片段包装在异常处理器内,然后编写从事实际工作的部分,假设一切都工作正常。 例如:

 1 def doStuff():                  # Python code
 2         doFirstThing()          # We don‘t care about exceptions here,
 3         doNextThing()           # so we don‘t need to detect them
 4         ...
 5         doLastThing()
 6 
 7 if __name__ == __main__:
 8         try:
 9                 doStuff()       # This is where we care about results,
10         except:                 # so it‘s the only place we must check
11                 badEnding()
12         else:
13                 goodEnding()
14         ...

在Python代码中,完全没有必要让所有代码都去预防错误的发生,因为一旦有异常发生,运行Python代码的控制权就会立即跳转到相应的异常处理程序。再者,因为Python解释器会自动检查错误,所以Python代码通常不需要事先检查错误。归根结底一句话,异常(Exception)让程序员大致上可以忽略罕见的情况,并避免编写那些(烦人的但又不得不写的)错误检查代码。 //英文原文如下:

Because control jumps immediately to a handler when an exception occurs, there‘s
no need to instrument all your code to guard for errors. Moreover, because
Python detects errors automatically, your code usually doesn’t need to check for
errors in the first place. The upshot is that exceptions let you largely ignore
the unusual cases and avoid error-checking code.

 

1. Why Use Exceptions? 为什么使用异常

In a nutshell, exceptions let us jump out of arbitrarily large chunks of a program.

简而言之,异常让我们从一个程序中任意大的代码块中跳将出来。

技术分享

2. Exception Roles 异常充当的最常见的几种角色

  • Error handling 错误处理
  • Event notification 事件通知
  • Special-case handling 特殊情况处理
  • Termination actions 行为终止
  • Unusual control flows 非常规控制流

技术分享

技术分享

3. Exceptions: The Short Story 异常处理简明教程

3.1 默认异常处理器

3.2 捕获异常

3.3 引发异常

3.4 用户定义的异常

3.5 终止行为

3.6 小结

 

参考资料:

1. Book: Learning Python, Fourth Edition : PART VII Exceptions and Tools

理解Python语言里的异常(Exception)