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.
Python code
7 linestry:
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
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
- Use `except (ValueError, TypeError)` to catch multiple related exceptions.
- 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
More from Errors & debugging
- Catch RecursionError and Fail Gracefully in Python easy
- Catch ValueError and print friendly message in Python easy
- Collect Multiple Validation Errors in Python Before Raising medium
- Handle ValueError and ZeroDivisionError in Python with try except easy
- How to Add a Correlation ID to Logging Records in Python medium
- How to Assert Preconditions with Descriptive Messages in Python easy
Keep learning
Related tutorials and quizzes for this topic.