Write a PHP function that throws a custom exception if a condition is not met.

<?php
function checkValue($value) {
    if ($value < 0) {
        throw new Exception("Value must be non-negative");
    }
    return $value;
}

// Example usage:
try {
    $result = checkValue(-5);
    echo "Result: $result";
} catch (Exception $e) {
    echo "Error: " . $e->getMessage();
}
?>

 

Post your Answer