如何捕获require_once / include_once异常?

时间:2013-03-24 12:59:21

标签: php exception include try-catch require

我试图编写类似的代码:

<?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>
        ";
    }
}

我尝试require_onceinclude_once,但try catch没有抓住异常。

我怎么能抓住这个致命错误/警告例外?

3 个答案:

答案 0 :(得分:12)

由于include / require不会抛出异常,因此请检查您要包含的文件是否存在且可读。例如:

$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.');
}

答案 1 :(得分:6)

这些函数正在抛出E_COMPILE_ERROR,并且不能像这样捕获。

要处理这些错误,请参阅set_error_handler

答案 2 :(得分:3)

这个解决方案(改编自here)对我很好:

register_shutdown_function('errorHandler');

function errorHandler() { 
    $error = error_get_last();
    $type = $error['type'];
    $message = $error['message'];
    if ($type == 64 && !empty($message)) {
        echo "
            <strong>
              <font color=\"red\">
              Fatal error captured:
              </font>
            </strong>
        ";
        echo "<pre>";
        print_r($error);
        echo "</pre>";
    }
}