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
- Validating function arguments to ensure they’re in acceptable ranges or sets
- Handling user input that needs specific formatting or value constraints
- Enforcing value restrictions in custom data types or classes
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'
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.
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
Related Resources
Tutorial
Python's Built-in Exceptions: A Walkthrough With Examples
In this tutorial, you'll get to know some of the most commonly used built-in exceptions in Python. You'll learn when these exceptions can appear in your code and how to handle them. Finally, you'll learn how to raise some of these exceptions in your code.
For additional information on related topics, take a look at the following resources:
- Python's raise: Effectively Raising Exceptions in Your Code (Tutorial)
- Strings and Character Data in Python (Tutorial)
- Numbers in Python (Tutorial)
- Python's Built-in Exceptions: A Walkthrough With Examples (Quiz)
- Using raise for Effective Exceptions (Course)
- Python's raise: Effectively Raising Exceptions in Your Code (Quiz)
- Strings and Character Data in Python (Course)
- Python Strings and Character Data (Quiz)