Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何处理特定的未捕获异常?_Python_Python 3.x_Exception_Exception Handling - Fatal编程技术网

Python 如何处理特定的未捕获异常?

Python 如何处理特定的未捕获异常?,python,python-3.x,exception,exception-handling,Python,Python 3.x,Exception,Exception Handling,我希望在单个位置处理脚本中的一个特定异常,而不必每次都使用try/exceptionexception*。我希望下面的代码可以做到这一点: import sys def handle(exc_type, exc_value, exc_traceback): if issubclass(exc_type, ValueError): print("ValueError handled here and the script continues") retur

我希望在单个位置处理脚本中的一个特定异常,而不必每次都使用
try
/
exception
exception*。我希望下面的代码可以做到这一点:

import sys

def handle(exc_type, exc_value, exc_traceback):
    if issubclass(exc_type, ValueError):
        print("ValueError handled here and the script continues")
        return
    # follow default behaviour for the exception
    sys.__excepthook__(exc_type, exc_value, exc_traceback)

sys.excepthook = handle

print("hello")
raise ValueError("wazaa")
print("world")
a = 1/0
当时的想法是,
ValueError
将被“手动”处理,脚本将继续运行(
return
)。对于任何其他错误(
ZeroDivisionError
,在上述情况下),正常的回溯和脚本崩溃将随之发生

发生的是

$ python scratch_13.py
hello
ValueError handled here and the script continues

Process finished with exit code 1
其中提到(我的重点)

当引发异常并取消捕获时,解释器调用
sys.excepthook
有三个参数,exception类,exception 实例和一个回溯对象。在本周的互动会议中 在控件返回到提示符之前发生 编程这发生在程序退出之前

这意味着,当我在
handler()
中时,已经太晚了,因为脚本已经决定无论如何都要终止,我唯一的可能性就是影响回溯的效果

是否有方法全局忽略脚本中的特定异常?



*这适用于调试上下文,通常会引发异常并使脚本崩溃(在生产环境中),但在某些特定情况下(例如开发平台),只需丢弃此特定异常即可。否则,我会在可能出现问题的任何地方放置一个
try
/
exception
子句。

一种方法是使用并拥有一个受抑制异常的全局元组:

 suppressed = (ValueError,)
然后,在任何可能发生错误的地方,您只需使用suppress(*supprested)将其包装在
中即可:

然后在生产中,您只需将
抑制的
更改为
()


我想这是你能做的最好的了。你不能在全局范围内完全忽略这个异常,但是你可以这样做,这样你只需要就地更改

看一下可能会有帮助。@mulliganaire:我不明白:除了
,哪个
?你是说在密码里?如果是这样的话,这正是我想要避免做的事情(在所有地方添加
try
子句)@lalengua:这很有趣,但也意味着我必须在上下文管理器中包装整个脚本。不过,这是一个想法。当您捕获异常时,执行将从捕获异常的点继续;您不能返回到它被提出的位置,这意味着为异常类型提供一个全局“处理程序”不会特别有用。可能重复感谢,但这与
try
子句没有太大区别,在该子句中
except
将捕获特定异常并
传递
。我的目的不是修改脚本代码,而只是在一个地方处理异常,在脚本的正常流程之外。不,你的比到处都有try子句要好,因为正如你提到的,你可以全局修改行为。它仍然需要单独包装每个调用。@WoJ是的,但是如果不调整python解释器,就无法做得更好。
print("hello")
with suppress(*suppressed): # gets ignored
    raise ValueError("wazaa")
print("world")
a = 1/0 # raise ZeroDivisionError
suppressed = ()
print("hello")
with suppress(*suppressed):
    raise ValueError("wazaa") # raises the error
print("world")
a = 1/0 # doesn't get executed