【问题标题】:Error handling in python for custom exceptionspython中针对自定义异常的错误处理
【发布时间】:2021-06-15 03:02:00
【问题描述】:

我正在尝试对这些运算符设置错误异常。基本上,如果输入了列表中的项目以外的任何内容,我想抛出错误。我知道为什么这段代码不起作用,但我不知道如何修复它。请帮我完成这项工作。谢谢

while True:
        sign = ["+", "-" , "/" , "*"]
        try:
            operation_type=(input("what operation type you want to do?"))
            for i in range (len(sign)) :
                
                if (operation_type!= sign[i]):
                    print ("pass")
                    raise Invalid
                    i+=1
                break
        except Invalid:
            print("Please input + or - or / or *")

【问题讨论】:

    标签: python python-3.x error-handling


    【解决方案1】:

    这是我发现效果最好的(我已经包含了应该解释一切的 cmets):

    sign = ["+", "-" , "/" , "*"]
    
    while True:
        operation_type=input("what operation type you want to do?")
    
        if operation_type in sign:#If the input is in one of the operations in sign, then quit.
            print(operation_type, 'passed')
            break#Break out of checking loop, as the requirement is met
    
        print('that is not the required operation')#Essentially your exception
             
     print('program done')
    

    我希望这就是你要找的东西!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-07
      • 2022-01-12
      • 2011-05-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多