How to handle invalid argument in PHP

3 Answers

0 votes
function divide($numerator, $denominator) {
    if (!is_numeric($numerator) || !is_numeric($denominator)) {
        throw new InvalidArgumentException("Both arguments must be numeric.");
    }
    if ($denominator == 0) {
        throw new InvalidArgumentException("Denominator cannot be zero.");
    }
    return $numerator / $denominator;
}

try {
    echo divide(8, 0);
} catch (InvalidArgumentException $e) {
    echo "Error: " . $e->getMessage() . "\n";
}

try {
    echo divide(8, "abc");
} catch (InvalidArgumentException $e) {
    echo "Error: " . $e->getMessage() . "\n";
}



/*
run:

ERROR!
Error: Denominator cannot be zero.
Error: Both arguments must be numeric.

*/

 



answered May 21, 2025 by avibootz
0 votes
function multiply(int $a, int $b): int {
    return $a * $b;
}

try {
    echo multiply(7, "abc");
} catch (TypeError $e) {
    echo "Error: " . $e->getMessage();
}



/*
run:

ERROR!
Error: multiply(): Argument #2 ($b) must be of type int, string given, called in main.php on line 8

*/

 



answered May 21, 2025 by avibootz
0 votes
function validateString($input) {
    if (!is_string($input)) {
        throw new InvalidArgumentException("Expected a string, got " . gettype($input));
    }
}

function say($name) {
    validateString($name);
    
    return "Hello, $name!";
}

try {
    echo say(3829);
} catch (InvalidArgumentException $e) {
    echo "Error: " . $e->getMessage();
}



/*
run:

ERROR!
Error: Expected a string, got integer

*/

 



answered May 21, 2025 by avibootz

Related questions

4 answers 334 views
4 answers 354 views
4 answers 301 views
4 answers 294 views
3 answers 244 views
6 answers 462 views
4 answers 352 views
...