【发布时间】:2021-07-05 23:15:35
【问题描述】:
我有以下 try 块:
try:
# depending on conditions, this can generate several types of errors
mymodule.do_stuff()
except Exception as e:
print("something went wrong, the error was :" + type(e).__name__)
我想捕捉来自do_stuff() 的潜在错误。经过反复试验,我能够通过打印 type(e).__name__ 值来生成可能由 do_stuff() 触发的潜在错误列表:
DoStuffInsufficientMemoryException
DoStuffInsufficientCPUException
DoStuffInsufficientDiskException
但如果我尝试将我的 except 语句从 except Exception as e 修改为 except DoStuffInsufficientMemoryException,我将收到 DoStuffInsufficientMemoryException 未定义的错误。
我尝试定义一个扩展 Exception 的类,正如这里的大多数教程/问题所建议的那样,基本上:
class WAFInvalidParameterException(Exception):
pass
所以现在该变量已被识别,但由于我无法控制do_sutff() 将引发的错误,所以我不能在我的初始尝试块中真正raise 这个异常。
理想情况下,我希望每个错误都有 1 个 except 块,所以我希望有类似的内容:
try:
mymodule.do_stuff()
except DoStuffInsufficientMemoryException:
free_memory()
except DoStuffInsufficientCPUException:
kill_processes()
except DoStuffInsufficientDiskException:
free_disk_space()
但这当然行不通,因为这些变量没有定义。
【问题讨论】:
标签: python python-3.x exception error-handling