Last modified: May 19, 2025 By Alexander Williams

Handle ValueError Exception in Python

A ValueError occurs when a function receives an argument with the right type but an invalid value. This guide explains how to handle it.

Understanding and managing this exception is key to writing robust Python code. Let's dive into practical solutions.

What is ValueError?

ValueError is a built-in Python exception. It is raised when an operation or function receives an argument with the correct type but an inappropriate value.

For more details, read our guide on What is ValueError in Python?.

Common Causes of ValueError

This error often occurs when converting strings to numbers, slicing sequences, or using built-in functions. Examples include invalid type conversions or out-of-range values.

Check our article on Common Causes of ValueError in Python for a deeper look.

Handling ValueError with try-except

The best way to handle ValueError is using a try-except block. This catches the exception and allows graceful handling.


try:
    num = int("abc")
except ValueError:
    print("Invalid integer conversion")


Invalid integer conversion

Providing Default Values

You can provide a default value when a ValueError occurs. This keeps your program running smoothly.


def safe_convert(val):
    try:
        return int(val)
    except ValueError:
        return 0

print(safe_convert("123"))  # Works
print(safe_convert("abc"))  # Returns 0


123
0

Validating Input Before Conversion

Preventing ValueError is better than handling it. Validate input using methods like isdigit() before conversion.


user_input = "123a"
if user_input.isdigit():
    num = int(user_input)
else:
    print("Input must be digits only")


Input must be digits only

Handling Multiple Exceptions

You can catch multiple exceptions in one block. This is useful when different errors need similar handling.


try:
    num = int("abc")
except (ValueError, TypeError) as e:
    print(f"Error occurred: {e}")


Error occurred: invalid literal for int() with base 10: 'abc'

Raising Custom Error Messages

Sometimes you want to raise a ValueError with a custom message. This makes debugging easier.


age = -5
if age < 0:
    raise ValueError("Age cannot be negative")


ValueError: Age cannot be negative

Using Finally for Cleanup

The finally block executes whether an exception occurs or not. Use it for cleanup tasks.


try:
    num = int("123")
except ValueError:
    print("Conversion failed")
finally:
    print("This always runs")


This always runs

Best Practices for Handling ValueError

Always be specific about which exceptions you catch. Avoid bare except clauses. Provide helpful error messages.

For more tips, see Understanding ValueError in Python.

Conclusion

Handling ValueError properly makes your Python code more robust. Use try-except blocks, validate inputs, and provide clear error messages.

Remember to handle exceptions gracefully while maintaining code readability. This approach leads to better maintainable applications.