简体   繁体   中英

Can't catch ValueError in Python

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?

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, eg

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM