【发布时间】:2021-08-12 16:29:16
【问题描述】:
这是我第一次尝试编写除发那科 CNC 控制器以外的任何东西。我不知道为什么,但这段代码返回两个异常,如果我从 else 中删除 raise Exception:它不会返回任何一个异常。我错过了什么?
cut_type=[input("Enter cut type Straight(S) or Arc(A)" )]# Add Taper later
try:
if 'S' in cut_type:
valid_type=['Y']
elif 's' in cut_type:
valid_type=['Y']
elif 'A' in cut_type:
valid_type=['Y']
elif 'a' in cut_type:
valid_type=['Y']
else:
valid_type=['N']
raise Exception('Cut Type not Valid')
except:
print('NOT VALID TYPE')
raise Exception('Cut Type not Valid')
print(valid_type)
如果我运行上面的代码,我会得到以下结果
Enter cut type Straight(S) or Arc(A)q
NOT VALID TYPE
Traceback (most recent call last):
File "Chip Break testing.py", line 21, in <module>
raise Exception('Cut Type not Valid')
Exception: Cut Type not Valid
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "Chip Break testing.py", line 24, in <module>
raise Exception('Cut Type not Valid')
Exception: Cut Type not Valid
如果我在从任一位置删除 raise Exception 的情况下运行它,我不会得到任何异常。我知道我遗漏了一些简单的东西,但我看不到它。
【问题讨论】:
-
在
else部分,Exception被引发raise Exception('Cut Type not Valid'),它被 bareexcept:捕获,其中引发另一个异常 -
您的预期行为是什么?对我来说,这听起来像是该程序的正确行为。你想让它做什么?
-
是的,这将是两个例外的原因。如果您删除 else 块,您将在
print(valid_type)上遇到错误,因为它从未被分配。您使用的输入是什么,您的预期输出是什么? -
如果类型无效,为什么要向
valid_type添加任何内容? -
您是否打算捕捉您自己在
else块内try中提出的错误?很难理解你在这里想要做什么