擅长:python、mysql、java
<p>伊恩·比金有一个很好的<a href="http://blog.ianbicking.org/2007/09/12/re-raising-exceptions/" rel="nofollow noreferrer">primer on re-raising</a>。在</p>
<p>作为推论,我的规则是只捕捉代码知道如何处理的异常。很少有方法真正符合这个规则。例如,如果我正在读取一个文件,并且抛出了一个IOException,那么这个方法几乎没有什么合理的功能。在</p>
<p>作为一个推论,如果您可以返回到一个良好的状态,并且不只是想将用户抛出,那么在“main”中捕捉异常是合理的;这只在交互式程序中获得。在</p>
<p>《初级读本》中的相关章节是最新的:</p>
<pre><code>try:
a()
except:
exc_info = sys.exc_info()
try:
g()
except:
# If this happens, it clobbers exc_info,
# which is why we had to save it above
import traceback
print >> sys.stderr, "Error in revert_stuff():"
# py3 print("Error in revert_stuff():", file=sys.stderr)
traceback.print_exc()
raise exc_info[0], exc_info[1], exc_info[2]
</code></pre>
<p>在python3中,<a href="https://stackoverflow.com/questions/15838224/python3-re-raising-an-exception-with-custom-attribute">final raise could be written as</a>:</p>
^{pr2}$