1.什么是Python ValueError? (1. What is Python ValueError?)
Python ValueError is raised when a function receives an argument of the correct type but an inappropriate value. Also, the situation should not be described by a more precise exception such as IndexError.
当函数接收正确类型但值不合适的参数时,将引发Python ValueError。 同样,不应使用诸如IndexError之类的更精确的异常来描述这种情况。
2. ValueError示例 (2. ValueError Example)
You will get ValueError with mathematical operations, such as square root of a negative number.
您将通过数学运算获得ValueError,例如负数的平方根。
>>> import math
>>>
>>> math.sqrt(-10)
Traceback (most recent call last):
File "", line 1, in ValueError: math domain error
>>>
3.处理ValueError异常 (3. Handling ValueError Exception)
Here is a simple example to handle ValueError exception using try-except block.
这是一个使用try-except块处理ValueError异常的简单示例。
import math
x = int(input('Please enter a positive number:\n'))
try:
print(f'Square Root of {x} is {math.sqrt(x)}')
except ValueError as ve:
print(f'You entered {x}, which is not a positive number.')
Here is the output of the program with different types of input.
这是具有不同输入类型的程序输出。
Please enter a positive number:
16
Square Root of 16 is 4.0
Please enter a positive number:
-10
You entered -10, which is not a positive number.
Please enter a positive number:
abc
Traceback (most recent call last):
File "/Users/pankaj/Documents/PycharmProjects/hello-world/journaldev/errors/valueerror_examples.py", line 11, in x = int(input('Please enter a positive number:\n'))
ValueError: invalid literal for int() with base 10: 'abc'
Our program can raise ValueError in int() and math.sqrt() functions. So, we can create a nested try-except block to handle both of them. Here is the updated snippet to take care of all the ValueError scenarios.
我们的程序可以在int()和math.sqrt()函数中引发ValueError。 因此,我们可以创建一个嵌套的try-except块来处理它们。 这是更新的代码片段,用于处理所有ValueError方案。
import math
try:
x = int(input('Please enter a positive number:\n'))
try:
print(f'Square Root of {x} is {math.sqrt(x)}')
except ValueError as ve:
print(f'You entered {x}, which is not a positive number.')
except ValueError as ve:
print('You are supposed to enter positive number.')
4.在函数中引发ValueError (4. Raising ValueError in a function)
Here is a simple example where we are raising ValueError for input argument of correct type but inappropriate value.
这是一个简单的示例,其中我们为正确类型但值不合适的输入参数引发ValueError。
import math
def num_stats(x):
if x is not int:
raise TypeError('Work with Numbers Only')
if x < 0:
raise ValueError('Work with Positive Numbers Only')
print(f'{x} square is {x * x}')
print(f'{x} square root is {math.sqrt(x)}')
5.参考 (5. References)
Python Exception Handling
Python异常处理
ValueError Python Docs
ValueError Python文档
翻译自: https://www.journaldev.com/33500/python-valueerror-exception-handling-examples