Python ValueError异常处理示例

时间:2020-02-23 14:43:39  来源:igfitidea点击:

1.什么是Python ValueError?

当函数接收正确类型但值不正确的参数时,将引发Python ValueError。
另外,不应使用诸如IndexError之类的更精确的异常来描述这种情况。

2. ValueError示例

您将通过数学运算获得ValueError,例如负数的平方根。

>>> import math
>>> 
>>> math.sqrt(-10)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: math domain error
>>>

3.处理ValueError异常

这是一个使用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.')

这是具有不同输入类型的程序输出。

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/hyman/Documents/PycharmProjects/hello-world/theitroad/errors/valueerror_examples.py", line 11, in <module>
  x = int(input('Please enter a positive number:\n'))
ValueError: invalid literal for int() with base 10: 'abc'

我们的程序可以在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

这是一个简单的示例,其中我们为正确类型但值不合适的输入参数引发ValueError。

import math

def num_stats(x):
  if x is not int:
      raise TypeError('Work with Numbers Only')
  if x < 0:
      raise ValueError(&#039;Work with Positive Numbers Only&#039;)

  print(f&#039;{x} square is {x * x}&#039;)
  print(f&#039;{x} square root is {math.sqrt(x)}&#039;)