在Python中传递异常

2024-06-06 15:13:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一些代码可以执行一些功能异常处理,一切都很好,异常在我希望的时候就会出现,但是在调试时,行跟踪并不总是按照我的要求执行。

示例A:

>>> 3/0
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ZeroDivisionError: integer division or modulo by zero

示例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

在这两个例子中,异常确实发生在第1行,我们试图执行3/0,但是在后一个例子中,我们被告知它发生在第2行,在第2行中它被引发。

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

Tags: orinmoststdinlineintegercallfile
2条回答

作为参考,解决方案大致如下:

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)

其中最漂亮的部分是,您可以绕过变量e并将其metaraise到其他地方,即使在这一过程中遇到了其他异常。

当你提出一个你发现的异常时,比如

except Exception as e: raise e

它重置堆栈跟踪。就像重新提出一个新的例外。你想要的是:

except Exception as e: raise

相关问题 更多 >