首页 > 解决方案 > 如何在 Python 中捕获我的异常引发并再次反弹

问题描述

我正在尝试引发一个句柄异常,抓住他并再次引发它。问题是我无法保留该异常并导致程序在我捕获异常时再次停止。

我已经尝试过这种方式和其他一些方式并没有成功

try:

    if not (1 == 2):
        raise ValueError("This is my exception")


except Exception as error:

    raise ValueError(error)   # Trying to throw the previous exception

提前致谢

标签: pythonexceptiontry-catchexcept

解决方案


如果您希望引发被捕获的异常,您需要做的就是使用raise

try:
    ...
except:
    raise  # this will re-raise the exception that was caught

Python 3 允许您作为另一个异常的结果引发异常,从而为您提供有关根本原因的更多信息的回溯。

try:
    ...
exception Exception as e:
    raise CustomException('message') from e

推荐阅读