Python ValueError 예외 처리 예제
1. 파이썬 ValueError란 무엇입니까?
Python ValueError는 함수가 올바른 유형의 인수를 받았지만 부적절한 값을 받았을 때 발생합니다. 또한 상황은 IndexError와 같은 더 정확한 예외로 설명되어서는 안 됩니다.
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/pankaj/Documents/PycharmProjects/hello-world/journaldev/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. 참고문헌
- 파이썬 예외 처리
- ValueError 파이썬 문서