1

I know that we try catch in PHP to catch Exceptions, but about half of my interviewers said that try catch can catch a fatal error. I tried it and it doesn't work that way by default. Function set_error_handler can catch errors. And now I have doubts. Is there some way to configure PHP so it can catch a fatal error (or other errors) with try catch? I got doubts, because I found this pieces of code in my project

try {
//sometimes $sFile is not initialized 
    $sPath = $sProducerOutput . $sFile;
} catch (\Exception $oException) {
    $sPath = false;
}

try {
    $sJson = json_encode($aArgs['sJson']);
}
catch(\Exception $oException) {
    $bError    = true;
    $sMessage .= 'Unable to json_encode: ' . print_r($aArgs['sJson'], true) . ')'."\n";
}
Hevyweb
  • 402
  • 1
  • 5
  • 18
  • 1
    See https://stackoverflow.com/questions/277224/how-do-i-catch-a-php-fatal-error – Jack Skeletron May 28 '18 at 09:15
  • None of these snippets should produce a *fatal* error. They won't by default produce catchable exceptions either, unless you turn them into exceptions. – deceze May 28 '18 at 09:23
  • Yes, they don't throw exception but they can produce warnings. So is it possible to configure PHP so that it throws exception instead of warning? – Hevyweb May 28 '18 at 11:30
  • Possible duplicate of [How do I catch a PHP Fatal Error](https://stackoverflow.com/questions/277224/how-do-i-catch-a-php-fatal-error) – Nico Haase May 28 '18 at 11:30
  • No, It's not a duplicate. I know there is a function which handles errors. My question that about try catch. – Hevyweb Jun 05 '18 at 12:08

0 Answers0