【发布时间】:2019-11-03 07:06:12
【问题描述】:
让我们假设,一个代码由近 50 行组成,它有一个 try 块。考虑try 块有10 个未知错误的情况。是否可以在不指定 except 子句中的错误名称的情况下处理这些异常?
这里是示例代码:
try:
a = 2
b = 2 / 0
if 7 > 5:
print(7)
except(ZeroDivisionError, IndentationError)
print("Exception Handled")
在上述情况下,我知道 try 块中发生的错误的名称(比如-ZeroDivisionError 和 IndentationError)
如果错误名称未知怎么办?
【问题讨论】:
-
except Exception捕获所有异常 -
请注意,关于@DeveshKumarSingh,您通常不想捕获一般的
Exception,因为这样您将很难在代码中发现错误。 -
是的,我试过了,但我仍然遇到运行时错误
-
您尝试了什么,请将其添加到问题中,并且您在 except 子句中缺少
: -
根据这里的答案:stackoverflow.com/questions/6470428/… - except (ZeroDivisionError, IndentationError) as e: # do stuff