ValueError
ValueError
is a built-in exception that gets raised when a function or operation receives an argument with the right type but an invalid value. It means the argument’s type is okay, but its actual value isn’t acceptable for the operation at hand.
You can handle ValueError
to gracefully deal with invalid input, so your program doesn’t crash unexpectedly and can give your users helpful feedback.
ValueError
Occurs When
ValueError
Can Be Used When
ValueError
Examples
Here’s an example where Python raises a ValueError
when you try converting a string that doesn’t represent a valid number into an integer:
>>> int("one")
Traceback (most recent call last):
...
ValueError: invalid literal for int() with base 10: 'one'
Copied!
You can handle ValueError
with a try
… except
block to show a user-friendly message or choose an alternative action:
>>> user_input = "one"
>>> try:
... number = int(user_input)
... except ValueError:
... print(f"Could not convert '{user_input}' to an integer.")
...
Could not convert 'one' to an integer.
Copied!
If you’re writing a function that demands certain value constraints, you can raise ValueError
to enforce them:
>>> def set_age(age):
... if age < 0:
... raise ValueError("Age can't be negative")
... print(f"Age is {age} years")
>>> set_age(-5)
Traceback (most recent call last):
...
ValueError: Age can't be negative
Copied!
For additional information on related topics, take a look at the following resources:
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4