Python 中的异常传递
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4730435/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Exception Passing In Python
提问by Kevin Dolan
I have a bit of code that does some functional exception handling and everything works well, exceptions are raised when I want them to be, but when I'm debugging, the line-traces don't always do quite what I want them to.
我有一些代码可以进行一些功能性异常处理,并且一切正常,当我想要它们时会引发异常,但是当我调试时,行跟踪并不总是按照我想要的方式进行。
Example A:
示例 A:
>>> 3/0
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ZeroDivisionError: integer division or modulo by zero
Example B:
示例 B:
>>> try: 3/0
... except Exception as e: raise e
...
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
ZeroDivisionError: integer division or modulo by zero
In both of these examples, the exception really occurs in line 1, where we attempt to do 3/0, but in the latter example, we are told it has occurred on line 2, where it is raised.
在这两个示例中,异常确实发生在第 1 行,我们尝试执行 3/0,但在后一个示例中,我们被告知它发生在第 2 行,并在该行引发。
Is there a way in Python to raise an exception, as if it were another exception, something that would produce the following output:
Python 中是否有一种方法可以引发异常,就好像它是另一个异常一样,会产生以下输出:
>>> try: 3/0
... except Exception as e: metaraise(e)
...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ZeroDivisionError: integer division or modulo by zero
采纳答案by Kevin Dolan
For reference, the solution is approximately as follows:
作为参考,解决方案大致如下:
def getException():
return sys.exc_info()
def metaraise(exc_info):
raise exc_info[0], exc_info[1], exc_info[2]
try: 3/0
except:
e = getException()
metaraise(e)
The beautiful part of this is that you can then pass around the variable e and metaraise it somewhere else, even if other exceptions have been encountered along the way.
这样做的美妙之处在于,您可以传递变量 e 并将其元化到其他地方,即使在此过程中遇到了其他异常。
回答by Falmarri
When you re-raise an exception that you caught, such as
当您重新引发您捕获的异常时,例如
except Exception as e: raise e
it resets the stack trace. It's just like re-raising a new exception. What you want is this:
它重置堆栈跟踪。这就像重新提出一个新的例外。你想要的是这个:
except Exception as e: raise

