我正在研究扣除金额函数,如果值中 a < b,它应该会引发运行时错误:
这是我的代码
def deduct_amount(a, b):
try:
b - a < 0
except ValueError:
print(a + ' can not be less than' + b)
else:
c = a - b
return c
deduct_amount(8, 12)
Run Code Online (Sandbox Code Playgroud)
我知道我的 try 语句是错误的。如果 a 小于 b,如何抛出值错误
块try/except是为了捕获异常。你想要raise一个例外:
if a > b:
raise ValueError("a must be less than b")
Run Code Online (Sandbox Code Playgroud)