Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,894 questions

51,825 answers

573 users

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 213 views
4 answers 239 views
4 answers 192 views
4 answers 199 views
3 answers 172 views
6 answers 277 views
4 answers 205 views
...