python - 在 except 中引发异常而不调用原始异常

标签 python exception nested raise

我的代码如下:

try:
    *Do something*
except *anError*:
    if (condition):
        methodCalled()
    else:
        raise "my own Exception"

问题是,当我引发自己的异常(“我自己的异常”)时,也会引发“anError”异常。有没有办法确保当我引发自己的异常时,我捕获的错误不会引发?

最佳答案

引用docs :

When raising (or re-raising) an exception in an except or finally clause __context__ is automatically set to the last exception caught; if the new exception is not handled the traceback that is eventually displayed will include the originating exception(s) and the final exception.

这正是您的情况:

try:
    try:
        raise ValueError
    except ValueError:
        raise TypeError
except Exception as e:
    print('Original:', type(e.__context__)) # Original: <class 'ValueError'>
    print('Explicitly raised:', type(e))    # Explicitly raised: <class 'TypeError'>

只有一个事件异常;我可能写了 except TypeError 而不是 except Exception ,并且输出仍然是相同的。

如果要阻止 Python 打印原始异常,请使用 raise ... from None :

try:
    raise ValueError
except ValueError:
    raise TypeError from None

关于python - 在 except 中引发异常而不调用原始异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28028173/

相关文章:

python - 决策树可视化期间位置参数遵循关键字参数错误

java - 如何在java中使用TimeUnit

python - python中离散功率谱密度的正确归一化实际问题

python - 从每行/etc/hosts 获取主机名值

c++ - 这个 "trick"跨 DLL 边界抛出异常是个坏主意吗?

java - 如何解决cassandra中的写超时异常?

excel - 用于文本(、格式)转换的嵌套字符串

javascript - 了解 JQGrid 中网格嵌套的级别

用于嵌套 Div 标签的 PHP RegEx

用于多个 MapReduce 步骤的 Python 工作流引擎