且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

无法在 Python 中捕获 ValueError

更新时间:2022-02-10 09:43:15

在您进入 try 块之前发生崩溃.如果您使用当前代码输入一个字母,它不会在 except 块中打印错误.

The crash is occurring before you enter the try block. It does not print the error in the except block if you enter a letter with your current code.

简单地将输入部分放在单独的 try 块中不会捕获它 - 您需要一个与发生错误的 try 相关的 except 块,例如

Simply putting the input section in a separate try block wouldn't catch it - you need an except block related to the try within which the error is happening, e.g.

try:
    a = float(input('num1: '))
    b = float(input('num2: '))
except ValueError as e:
    print ('Value Error')

try:
    result = a / b
except ZeroDivisionError as e:
    print ('Zero DivisionError')

print(result)

或者,您可以将输入和除法全部放在 try 块中并捕获当前报告:

Alternatively, you could put the input and division all within the try block and catch with your current reporting:

try:
    a = float(input('num1: '))
    b = float(input('num2: '))
    result = a / b
except ValueError as e:
    print ('error type: ', type (e))

print(result)

请注意,如果其中任何一个发生任何错误,稍后都会导致进一步的错误.您***使用第二个选项,但将打印(结果)移动到 try 块中.这是唯一一次定义它.

Note that if any error does occur in either of these, it will cause further errors later on. You're better off going with the second option, but moving the print(result) into the try block. That's the only time it will be defined.