Python 3 异常处理抛出错误

Nit*_*hin 1 python exception-handling python-3.x

我上周开始学习 python,但我无法理解这里有什么问题:

def add(x,y):
    """Adds 2 numbers and returns the result"""
    return x+y

def sub(x,y):
    """Subtracts 2 numbers and returns the result"""
    return x-y


a = int(input("Enter first number"))
b = int(input("Enter second number"))
c = int(input("Enter 1 for subtraction , 2 for addition and 3 for both"))
try:
    if c>3:
        raise ValueError()
except ValueError():
    print ("Wrong choice")
else:
    print ("Your choice is ",c)
if (c==1):
    print ("Subtraction of 2 numbers=",(sub(a,b)))
if (c==2):
    print ("Addition of 2 numbers = ",(add(a,b)))
if (c==3):
    print ("Subtraction of 2 numbers=",(sub(a,b)))
    print ("Addition of 2 numbers = ",(add(a,b)))
Run Code Online (Sandbox Code Playgroud)

如果我输入 4 它会抛出这个错误:

Traceback (most recent call last):
  File "C:/Program Files (x86)/Python35-32/calculator.py", line 15, in <module>
    raise ValueError()
ValueError
Run Code Online (Sandbox Code Playgroud)

在处理上述异常的过程中,又发生了一个异常:

Traceback (most recent call last):
  File "C:/Program Files (x86)/Python35-32/calculator.py", line 16, in <module>
    except ValueError():
TypeError: catching classes that do not inherit from BaseException is not allowed
Run Code Online (Sandbox Code Playgroud)

Mar*_*ers 8

您正在试图赶上一个实例ValueError(),其中Python的希望您能在过滤器类型。删除调用:

except ValueError:
    print ("Wrong choice")
Run Code Online (Sandbox Code Playgroud)