Can't catch symfony FatalErrorException

后端 未结 4 445
感情败类
感情败类 2020-12-29 19:29

I have code like this:

try {
    $var = $object->getCollection()->first()->getItem()->getName();
} catch(\\Exception $e) {
    $var = null;
}
         


        
4条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2020-12-29 19:55

    As you can see here, FatalErrorException extends ErrorException (PHP) that extends itself php Exception class.

    Now that you have all this elements, you're ready for next step: as the name of exception says, this is a FatalError (a concept related to PHP and not with Symfony2; in that case they built a wrapper class for this error, maybe for interface purposes).

    A PHP fatal error isn't a catchable one so is pretty useless to keep the code that could cause the FatalError, inside a try ... catch block

    You should check, as a common and good rule, whenever is possible for returned values before try to access them.

    Update

    Since I've seen an upvote to my answer after PHP7 was released, I would like to caveat that since PHP7 is possible to catch fatal errors so this answer is still valid but only for PHP versions < 7.

提交回复
热议问题