2

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

  • It's a warning, not an exception. Run a simple test `if ($dividor === 0) { $a = 99; }` – Qirel Feb 15 '20 at 12:34
  • @Qirel then why this solution worked for me ? try{ $a=112/0; }catch(\Exception $e){ $a=99; } – Hafijur Rahman Sakib Feb 15 '20 at 12:48
  • @HafijurRahmanSakib Because Laravel turns all PHP warnings into ErrorException Instance. Check this out: [Illuminate/Foundation/Bootstrap/HandleExceptions.php](https://github.com/laravel/framework/blob/5.3/src/Illuminate/Foundation/Bootstrap/HandleExceptions.php#L27-L42) – Qumber Feb 15 '20 at 13:07

2 Answers2

2

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
}
Qumber
  • 13,130
  • 4
  • 18
  • 33
  • 1
    You can't do it with a try/catch to begin with, because its not an exception. – Qirel Feb 15 '20 at 12:43
  • @Qirel Looks like, in case of Laravel, you can. See this: https://stackoverflow.com/questions/40548258/how-laravel-handles-php-warnings – Qumber Feb 15 '20 at 13:09
0

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;
}
TsaiKoga
  • 12,914
  • 2
  • 19
  • 28