You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python自定义异常抛出疑问:为何仍显示ZeroDivisionError?

Python异常处理疑问:except块中抛出新异常时原异常为何仍显示?

我刚接触Python异常处理,编写了如下代码后产生诸多疑问:

class CustomException(Exception):
    def __init__(self,msg):
        self.msg=msg
        print( 'custom exception occurred')

class Test:
    def __init__(self):
        self.func1()

    def func1(self):
        try:
            print(40/0)
        except Exception as e:
            print("entered exception block")
            raise CustomException("Error message")
obj=Test()

测试情况

  • 当注释掉raise CustomException("Error message")语句时,程序执行except块中的打印操作,且不会输出回溯栈;
  • 保留print和raise语句时,得到如下输出:
entered exception block
custom exception occurred
Traceback (most recent call last):
  File "c:\Users\inavis\Desktop\customException1.py", line 12, in func1
    print(40/0)
          ~~^~
ZeroDivisionError: division by zero

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "c:\Users\inavis\Desktop\customException1.py", line 16, in <module>
    obj=Test()
        ^^^^^^
  File "c:\Users\inavis\Desktop\customException1.py", line 8, in __init__
    self.func1()
  File "c:\Users\inavis\Desktop\customException1.py", line 15, in func1
    raise CustomException("Error message")
CustomException: Error message

核心疑问

我理解自定义异常是因为主动抛出才出现,但为何ZeroDivisionError也会显示?既然print和raise语句都在该except块中,难道不意味着ZeroDivisionError已被处理了吗?


解答

  1. 注释raise时无回溯的原因
    当你注释掉raise语句时,ZeroDivisionError确实已经被except块处理了——程序捕获到异常后执行了打印操作,没有再抛出任何未处理的异常,程序正常结束,所以不会输出回溯栈。

  2. 保留raise时原异常显示的原因
    Python的异常机制中,当你在处理一个异常(这里是ZeroDivisionError)的except块里抛出另一个新异常(CustomException)时,Python会自动将原异常设置为新异常的上下文(通过__context__属性)。当新异常没有被后续代码捕获,最终触发回溯时,Python会把整个异常链的信息都打印出来,告诉你"在处理前面那个异常的过程中,又发生了新的异常",这是为了帮你排查问题的完整链路。

简单说:你确实捕获了ZeroDivisionError,但处理它的过程中又抛出了未被捕获的CustomException,Python为了让你清楚问题的来龙去脉,就把两个异常的信息都展示了出来。

  1. 如何只显示新异常的回溯
    如果不想展示原异常的上下文,可以在raise时加上from None,这样就会切断异常链,只打印新异常的信息:
raise CustomException("Error message") from None

内容的提问来源于stack exchange,提问作者inavis

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 19:17:36