I'm trying to write code similar this:
<?php
$includes = array(
'non_existing_file.php', //This file doesn't exist.
);
foreach ($includes as $include) {
try {
require_once "$include";
} catch (Exception $e) {
$message = $e->getMessage();
echo "
<strong>
<font color=\"red\">
A error ocurred when trying to include '$include'.
Error message: $message
</font>
</strong>
";
}
}
I'd tried require_once
and include_once
, but try catch
doesn't catch the exception.
How could I catch this fatal errors/warning exceptions?
Since include/require does not throw an exception, check before if the file your want to include exists and is readable. eg:
$inc = 'path/to/my/include/file.php';
if (file_exists($inc) && is_readable($inc)) {
include $inc;
} else {
throw new Exception('Include file does not exists or is not readable.');
}
These functions are throwing E_COMPILE_ERROR, and are not catchable like this.
To handle these errors see set_error_handler.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With