Try catch block can not prevent run time exception in my Laravel code.
I wrote following code to test the exception handling:
try{
$a=112/0;
}catch(Exception $e){
$a=99;
}
But it returns a Run time error. Please help me to solve the issue.
Try this:
try{
$a=112/0;
}catch(\Exception $e){
$a=99;
}
Notice the \
before Exception
.
Update: As @Qirel suggests:
You can simply update your code to do it without try/catch:
if($d === 0){
$a = 99;
} else{
$a = 112/$d
}
Answer:
Because you are using php7 you need to use Throwable to catch the exception like this:
try{
$a=112/0;
}catch(Exception $e){
// For php 5
$a=99;
} catch(\Throwable $e) {
// For php7
$a=99;
}
Tags: laravel, php, phplaravel