无法在 Python 中捕获 ValueError [英] Can't catch ValueError in Python

查看:39
本文介绍了无法在 Python 中捕获 ValueError的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我开始学习Python,写了一个很简单的代码来练习try/except.

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

代码如下:

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 有效,但 ValueError 无效.

ZeroDivisionError & TypeError are working, but ValueError is not.

我什至将输入放在单独的 try/except 中,但它仍然无法正常工作.

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?

推荐答案

在您进入 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.

这篇关于无法在 Python 中捕获 ValueError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆