Catching ValueError in Python

In advanced computations, it’s common to work with mathematical functions that have domain restrictions. For instance, the math.sqrt() function only accepts non-negative numbers and will raise a ValueError if given a negative input. This example demonstrates how to use a try-except block to catch such errors, provide a clear message, and maintain robust code execution.


Code Example

import math

def safe_sqrt(value):
    """
    Returns the square root of the given value if it's non-negative.
    In case of a negative number, catches the ValueError and returns None.
    """
    try:
        # Attempt to calculate the square root
        result = math.sqrt(value)
    except ValueError as e:
        # Handle the exception by providing a clear error message.
        print(f"ValueError caught: {e}. Please provide a non-negative number.")
        result = None
    return result

# Demonstrate function usage with both valid and invalid inputs.
print("Square root of 16:", safe_sqrt(16))
print("Square root of -4:", safe_sqrt(-4))

Code Explanation

  • Function Overview:
    The function safe_sqrt takes one parameter (value) and attempts to compute its square root using math.sqrt().
  • Error Handling:
    Since math.sqrt() raises a ValueError when provided a negative number, the operation is wrapped in a try-except block. If a negative value is passed, the exception is caught, and an informative message is printed. Instead of stopping the program, the function returns None, thus enabling the caller to handle the error condition smoothly.
  • Usage Demonstration:
    The function is called twice:
    • With 16, where the square root is computed successfully.
    • With -4, where a ValueError occurs, gets caught, and None is returned while also printing a user-friendly error message.

This approach is particularly useful in production-level code where resilient error handling ensures the application continues to run, even when unexpected inputs are encountered.