Try to catch a failure

This is a simple question when one hour at Google does not seem to allow it. How do you catch failure in PHP? For the following code:

try { include_once 'mythical_file'; } catch (Exception $e) { exit('Fatal'); } echo '?'; 

With a mythical file that does not exist, I get the output of '?'. I know that PHP cannot catch failure because it causes a warning error, but here? What is the best way to catch failure? For example, the following works:

 (include_once 'unicorn') or exit('!'); 

but this does not throw an exception, so I cannot get the context of the file, line and stack.

+6
include php try-catch
source share
2 answers

You can use require_once instead of include_once

+2
source share

include and include_once trigger warning (E_WARNING) , require and require_once trigger (E_COMPILE_ERROR) . Therefore, you should use require or require_once .

Quote php.net:

"require () is identical to include () except in cases of failure, create a deadly level E_COMPILE_ERROR error. In other words, it will stop the script, while include () will issue a warning (E_WARNING) that allows the script to continue."

+1
source share

All Articles