phpexceptionyii2yii2-basic-app

Exception not able to get caught in catch block - Yii2


Exception

Exception 'Error' with message 'Class 'app\commands\CallLogs' not found'

is not able to get caught in catch block.

Code:

I tried with calling undefined class just to see how and what exception catch block catches.

public function actionTest(){
    try {
        $logs = new CallLogs();
    } catch (\yii\base\Exception $ex) {
        print $ex->getMessage();
    } catch(\ErrorException $ex){
        print $ex->getMessage();
    }
}

But, When I intentionally throw any exception, it works.

public function actionTest(){
    try {
        throw new \yii\base\Exception('hello');
    } catch (\yii\base\Exception $ex) {
        print $ex->getMessage();
    } catch(\ErrorException $ex){
        print $ex->getMessage();
    }
}

I have tried with base\Exception class and \ErrorException class. But, no help.

Any help/hint is appreciable


Solution

  • catch (\Throwable $e) will do the job

    \Throwable was introduced back in PHP 7.0 and is (quoting from docs) used for

    [...] any object that can be thrown via a throw statement, including Error and Exception.