PythonのValueError例外処理の例を挙げます。

「Python ValueError」は何ですか? (Python ValueError wa nan desu ka?)

PythonのValueErrorは、関数が適切な型の引数を受け取るが、不適切な値が渡された場合に発生します。また、この状況はIndexErrorなどのより詳細な例外で説明されるべきではありません。

2. ValueErrorの例

2.値エラーの例

数学的な計算(例えば、負の数の平方根など)では、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/scdev/Documents/PycharmProjects/hello-world/scdev/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('Work with Positive Numbers Only')

    print(f'{x} square is {x * x}')
    print(f'{x} square root is {math.sqrt(x)}')

5. 参考文献

  • Python Exception Handling
  • ValueError Python Docs
コメントを残す 0

Your email address will not be published. Required fields are marked *