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

  • Calling a function with an argument that has the right type but an inappropriate value
  • Converting strings to numbers and the string doesn’t represent a valid number

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:

Python
>>> int("one")
Traceback (most recent call last):
    ...
ValueError: invalid literal for int() with base 10: 'one'

You can handle ValueError with a tryexcept block to show a user-friendly message or choose an alternative action:

Python
>>> 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:

Python
>>> 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

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.

intermediate python

For additional information on related topics, take a look at the following resources:


By Leodanis Pozo Ramos • Updated March 13, 2025 • Reviewed by Dan Bader, and Martin Breuss