【问题标题】:newbie Raising an Exception新手引发异常
【发布时间】: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'),它被 bare except: 捕获,其中引发另一个异常
  • 您的预期行为是什么?对我来说,这听起来像是该程序的正确行为。你想让它做什么?
  • 是的,这将是两个例外的原因。如果您删除 else 块,您将在 print(valid_type) 上遇到错误,因为它从未被分配。您使用的输入是什么,您的预期输出是什么?
  • 如果类型无效,为什么要向valid_type添加任何内容?
  • 您是否打算捕捉您自己在else 块内try 中提出的错误?很难理解你在这里想要做什么

标签: python exception


【解决方案1】:

这是我在提出建议并重新检查我的代码以使其正常工作后所做的。

cut_type=[input("Enter cut type Straight(S) or Arc(A)" )]# Add Taper later
 
if 'S' in cut_type:
    pass    
elif 's' in cut_type:
    pass    
elif 'A' in cut_type:
    pass    
elif 'a' in cut_type:
    pass    
else:
    raise Exception('Cut Type not Valid')

谢谢大家。我希望能学到更多知识并转行。

【讨论】:

    猜你喜欢
    • 2012-01-13
    • 1970-01-01
    • 2019-03-14
    • 2011-01-04
    • 2020-07-31
    • 2021-10-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多