Python Glossary Русский

all Python 3Exceptionsexception

ValueError

built-in exceptions

Raised when a function gets an argument of the right type but with an unacceptable value. For example, int('abc') or math.sqrt(-1).

Syntax

raise ValueError('сообщение')

The line against TypeError is simple: the type fits, the value does not — int('abc') is a ValueError, while int([]) is a TypeError. int('12.5') fails too, because int() does not parse a fractional part; go through float() first. Put except ValueError around the narrow spot (int(input())) instead of wrapping a whole block in except Exception, or you will bury your own typos.

Examples

int('abc')           # ValueError
float('inf')         # ok — inf допустим
[1, 2, 3].index(99)  # ValueError: 99 нет в списке
try:
    x = int('нет')
except ValueError as e:
    print('Ошибка:', e)

See also

Open in the full glossarydocs.python.orgReport an inaccuracy