Python 教程 states:
The try ... except statement has an optional else clause, which, when present, must follow all except clauses. It is useful for code that must be executed if the try clause does not raise an exception. For example:
for arg in sys.argv[1:]: try: f = open(arg, 'r') except IOError: print 'cannot open', arg else: print arg, 'has', len(f.readlines()), 'lines' f.close()The use of the else clause is better than adding additional code to the try clause because it avoids accidentally catching an exception that wasn’t raised by the code being protected by the try ... except statement.
问题1> A&tej 看了上面的文档,还是不明白为什么不能简单的把代码从else子句移到try子句中。
问题 2> try 子句 是如何意外捕获异常的,因为所有这些捕获都是在 except 子句 中完成的,对吗?
请您参考如下方法:
您可以将 else 代码放在 try 套件中,但是您会捕获那里可能引发的任何异常。如果您不打算发生这种情况,那将是“意外”,因此您链接到的文档的措辞。
最佳做法是在 try block 中放置尽可能少的代码,以便在发生错误时,您知道是什么操作导致了它并可以适本地处理它。如果您在 try block 中有五行代码,并且只期望其中一行会引发异常,那么当异常发生在您没有的行中时,您的异常处理代码将准备不足不要期望它。在这种情况下,抛出异常比以错误的方式处理它更好。
