Can't catch ValueError in Python

十年热恋 提交于 2020-11-25 04:01:55

问题


I am starting to learn Python, and I wrote a very simple code to practice try/except.

Here is the code:

a = float(input('num1: '))
b = float(input('num2: '))

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

print(result)

Whenever I enter a letter as a number, the print in except is working, but the code crashes.

ZeroDivisionError & TypeError are working, but ValueError is not.

I even put inputs in separate try/except and it is still not working.

How can I handle this error here, and in the real app?


回答1:


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.

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)

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)

EDIT: 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.



来源:https://stackoverflow.com/questions/58354826/cant-catch-valueerror-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!