How to throw and catch exceptions with try - catch in PHP

1 Answer

0 votes
function div($a, $b) 
{
    if ($b == 0) 
        throw new Exception('Division by zero');
    return $a/$b;
}

try 
{
    echo div(10, 2) . "<br />";
    echo div(22, 0) . "<br />";
    echo div(60, 3) . "<br />";
} 
catch (Exception $e) 
{
    echo 'Exception: ' .  $e->getMessage() . '<br />';
}
 
 
echo "Countinue with the program"; 
 
/*
run:
 
5
Exception: Division by zero
Countinue with the program
 
*/

 



answered Jul 24, 2015 by avibootz
edited Jul 24, 2015 by avibootz

Related questions

3 answers 305 views
305 views asked Jan 3, 2016 by avibootz
2 answers 285 views
2 answers 286 views
1 answer 204 views
1 answer 182 views
182 views asked Dec 17, 2016 by avibootz
2 answers 347 views
2 answers 416 views
...