用于引发值错误的 try 和 except 块

Any*_*yta 0 python try-except

我正在研究扣除金额函数,如果值中 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,如何抛出值错误

Jab*_*Jab 6

try/except是为了捕获异常。你想要raise一个例外:

if a > b:
   raise ValueError("a must be less than b")
Run Code Online (Sandbox Code Playgroud)