Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to catch require_once/include_once exception?

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?

like image 669
GarouDan Avatar asked Mar 24 '13 12:03

GarouDan


2 Answers

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.');
}
like image 150
passioncoder Avatar answered Oct 06 '22 12:10

passioncoder


These functions are throwing E_COMPILE_ERROR, and are not catchable like this.

To handle these errors see set_error_handler.

like image 41
soyuka Avatar answered Oct 06 '22 12:10

soyuka