ValueError — Easy Examples
Raised when a function receives an argument of the right type but wrong value
Triggering ValueError
How ValueError is raised and how to catch it.
python
# Triggering and catching ValueError try: int("not_a_number") except ValueError as e: print(f"Caught ValueError: {e}") print(f"Type: {type(e).__name__}")
ValueError is raised when raised when a function receives an argument of the right type but wrong value. Always catch specific exceptions rather than bare except clauses.
Handling ValueError
Basic error handling pattern for ValueError.
python
# Safe handling pattern def safe_operation(): try: int("not_a_number") except ValueError: print("Operation failed gracefully") return None result = safe_operation() print(f"Result: {result}")
Wrapping risky operations in try/except blocks prevents your program from crashing.
Want to try these examples interactively?
Open Easy Playground