0

我在下面有一个代码示例,我想在其中捕获一些异常:

在主函数中:

try:
    ...
    do_something()
except some_exception,e:
    do_some_other_thing

do_something函数中

try:
    ...
except some_exception,e:
    do_some_other_thing

所以当我测试它时,我注意到异常被处理了两次(一次在do_somthing(),一次在main函数中),我的观察准确吗?

有没有办法捕获仅未被其函数捕获的异常?因为我想捕捉两种场景,它们在某种程度上被包装到同一个异常处理类中(即some_exception

4

2 回答 2

1

为什么不尝试一下,看看一个简单的测试会发生什么?

def main():
    try:
        raise ValueError("in main!")
    except ValueError as e:
        print "caught exception",str(e)
        #for fun, re-run with the next line uncommented and see what happens!
        #raise

try:
    main()
except ValueError:
    print "caught an exception above main"

如果您实际尝试此代码,您会注意到它只打印一条消息(在main函数内部),表明异常一旦被捕获就不会向上传播(除非您raise在 except 子句中重新设置)。

于 2012-12-17T21:08:43.000 回答
1

你的观察不准确;必须有 2 个地方 raise some_exeption,或者你明确地重新加注它。

一旦一个异常被正确捕获,它就不会被堆栈中更高的其他处理程序捕获。

这是最简单的演示:

>>> try:
...     try:
...         raise AttributeError('foo')
...     except AttributeError as e:
...         print 'caught', e
... except AttributeError as e:
...     print 'caught the same exception again?', e
... 
caught foo

仅调用了内部处理程序。 except另一方面,如果我们重新引发异常,您将看到两个处理程序都打印一条消息:

>>> try:
...     try:
...         raise AttributeError('foo')
...     except AttributeError as e:
...         print 'caught', e
...         raise e
... except AttributeError as e:
...     print 'caught the same exception again?', e
... 
caught foo
caught the same exception again? foo

As such, there is no need to have to handle 'exceptions that are not caught by the function'; you will only need to handle exceptions that were not already caught earlier.

于 2012-12-17T21:08:54.463 回答