How to Catch ValueError in Python

Shows how to handle a ValueError with try-except so a bad int() conversion doesn't crash the script.

Easy Python 3.9+ Aug 9, 2026 Errors & debugging 17 views 0 copies

Python code

7 lines
Python 3.9+
try:
    number = int("not_a_number")
    print(f"Parsed successfully: {number}")
except ValueError as e:
    print(f"Error: {e}")
    print("Please provide a valid integer.")
print("Program continues running.")

Output

stdout
Error: invalid literal for int() with base 10: 'not_a_number'
Please provide a valid integer.
Program continues running.

How it works

The try block runs the risky code first. When int() receives a non-numeric string, it raises a ValueError. The except ValueError as e clause catches that exact exception, giving you the error message via e. After the except block runs, execution continues normally with the print statement after the try-except. This is the core pattern for graceful error handling in Python.

Common mistakes

  • Catching too broadly with bare `except:` which hides unexpected errors.
  • Forgetting to print the actual error message from the exception object.
  • Assuming the except block stops the program — it doesn't; execution continues after try-except.
  • Not including the variable name `as e` to access error details.

Variations

  1. Use `except (ValueError, TypeError)` to catch multiple related exceptions.
  2. Add an `else` block to run code only when no exception occurs.

Real-world use cases

  • Validating user input from a command-line prompt before converting to a number.
  • Handling malformed JSON or CSV values that fail type conversion during data ingestion.
  • Gracefully recovering from bad API responses that pass non-numeric fields to int() or float().

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Errors & debugging

Related tutorials and quizzes for this topic.