How to Handle ValueError in Python (try except)
Learn to catch ValueError and other exceptions with try-except blocks in Python using practical division and string-to-float conversion examples.
Python code
29 linesdef divide_numbers(a, b):
"""Divide two numbers and handle ValueError safely."""
try:
result = a / b
return f"{a} / {b} = {result}"
except ZeroDivisionError:
return "Error: Cannot divide by zero!"
except TypeError:
return "Error: Both inputs must be numbers!"
def parse_float(value):
"""Convert a string to float, gracefully handling bad input."""
try:
converted = float(value)
return f"Converted '{value}' to {converted}"
except ValueError:
return f"Error: '{value}' is not a valid number!"
if __name__ == "__main__":
# Demonstrate division cases
print(divide_numbers(10, 2))
print(divide_numbers(7, 0))
print(divide_numbers(9, "3"))
# Demonstrate parsing cases
print(parse_float("3.14"))
print(parse_float("hello"))
Output
10 / 2 = 5.0
Error: Cannot divide by zero!
Error: Both inputs must be numbers!
Converted '3.14' to 3.14
Error: 'hello' is not a valid number!
How it works
This example shows how try-except catches specific exceptions without crashing the program. The except ValueError block only triggers when a value cannot be converted to a float, while except ZeroDivisionError handles division by zero. Multiple except clauses let you respond to different error types individually, keeping the code robust. Control flow continues after the except block, so later code still runs. This pattern is essential for user input validation and file processing where errors are common.
Common mistakes
- Catching Exception broadly instead of specific types, hiding bugs
- Forgetting that float('3.14') is valid but float('3.14abc') raises ValueError
- Not returning or raising after a caught exception, causing silent failure
- Placing a more general except before a specific one, making it unreachable
Variations
- Use a `try-except-else` block to run code only when no exception occurs
- Catch multiple exception types in one clause with `except (ValueError, TypeError)`
Real-world use cases
- Parsing user-entered numbers from a web form before storing them in a database.
- Converting command-line arguments or config file strings to numeric types.
- Handling malformed JSON or CSV values during data ingestion pipelines.
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.