Place the erroneous code in ‘try’ block, and handle the exceptions in catch block.
Example
try{
div(10, 0);
}catch(LogicException $e){
echo "Error Occurred : " . ($e -> getMessage()) . "\n";
}
Find the below working application.
try_catch_demo.php
#!/usr/bin/php
<?php
function div($a, $b){
if($b == 0){
throw new LogicException('Division by zero');
}
return $a /$b;
}
try{
div(10, 0);
}catch(LogicException $e){
echo "Error Occurred : " . ($e -> getMessage()) . "\n";
}
?>
Output
$./try_catch_demo.php
Error Occurred : Division by zero
No comments:
Post a Comment