Home » Php » php – Try catch not working in Laravel 5.6 when a number is divided by zero

php – Try catch not working in Laravel 5.6 when a number is divided by zero

Posted by: admin February 25, 2020 Leave a comment

Questions:

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.
Run time exception

How to&Answers:

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;
}