2

I am working with laravel 5.5 I have written a code with try and catch exception. But Try / catch is not manage exception handling. Exception execute on the Exception/handle.php

Here is code I am following

try {
 App\Models\justDoIt::find(1);
}  catch (\Exception $ex) {
       dd($ex);
       report($ex);
       return false;
}

I would like to know why catch is not executed and error is display from the handle.php in report()

Here is the handle.php code

public function report(Exception $exception) {
        echo "Handle";
        dd($exception);
        parent::report($exception);
    }

Result

Handle
FatalThrowableError {#284 ▼
  #message: "Class 'App\Http\Controllers\App\Models\justDoIt' not found"
  #code: 0
  #file: "D:\xampp7\htdocs\homeexpert_nik\app\Http\Controllers\HomeController.php"
  #line: 21
  #severity: E_ERROR
  trace: {▶}
}

Result will show from the handle.php file.

Nikunj K.
  • 8,779
  • 4
  • 43
  • 53
  • 1
    You can use `JustDoIt::findOrFail` – Rutvij Kothari Mar 29 '18 at 20:06
  • @RutvijKothari I have tried to use FindOrFail but still I got exception from handle? why this is so? why it's not execute catch Exception – Nikunj K. Mar 29 '18 at 20:11
  • Class not found exception is handled differently in PHP. You can find more information here: https://stackoverflow.com/questions/4421320/why-doesnt-php-catch-a-class-not-found-error – Rutvij Kothari Mar 29 '18 at 20:15

1 Answers1

8

Your code is throwing an error, not an exception. You're trying to use a class that doesn't exist and PHP is complaining about it by throwing a FatalThrowableError.

In PHP 5, this code would have resulted in a fatal error message being rendered in the browser, however in PHP 7 (Which is required for Laravel 5.5), PHP now throws errors just like they were exceptions. This allows applications to catch these errors, just like exceptions using try/catch blocks.

The reason the error is escaping your try/catch block is that an error is not an Exception, or a child of it. The object being thrown is an Error. Both the Exception and Error classes implement a common interface, Throwable.

Throwable
- Exception
- Error

Laravel's exception handler is written to catch both of these classes in order to display the error page you're seeing.

If you were to change your code to the following, you would find that the } catch (Throwable $e) { block should be executed:

try {
    App\Models\justDoIt::find(1);
} catch (\Exception $ex) {
   dd('Exception block', $ex);
} catch (\Throwable $ex) {
   dd('Throwable block', $ex);
}

For more information on this, see here.


An added extra: If you're wondering what the issue is with your code, it's because you likely forgot to use your model class in your controller:

use App\Models\justDoIt;
Jonathon
  • 15,873
  • 11
  • 73
  • 92