7

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?

Jason Aller
  • 3,541
  • 28
  • 38
  • 38
GarouDan
  • 3,743
  • 9
  • 49
  • 75

3 Answers3

17

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.');
}
passioncoder
  • 909
  • 6
  • 10
  • I wouldnt like this because the problem could not exist just as the file exists, but when requiring it. – GarouDan Mar 24 '13 at 14:00
  • good point. an additional `is_readable` would be much more better. – passioncoder Mar 24 '13 at 14:04
  • 1
    `include file.php;` could include this file from everywhere in the PHP include path. So `file_exists()` does not make sense here... Espacially if the programmer does not know how the include path will look like on the users server... – Peter Sep 08 '14 at 21:29
  • missing semicolon after `$inc = 'path/to/my/include/file.php'` – Chris Nov 16 '18 at 23:58
6

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

To handle these errors see set_error_handler.

soyuka
  • 8,839
  • 3
  • 39
  • 54
3

This solution (adapted from here) worked fine to me:

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>";
    }
}
Community
  • 1
  • 1
GarouDan
  • 3,743
  • 9
  • 49
  • 75