0

It's my understanding, per http://php.net/manual/en/language.errors.php7.php, that errors in PHP7 are now supposed to be thrown. But in my own testing this does not seem to be the case:

<?php

error_reporting(E_ALL);

try {
    echo $a[4];
} catch (Throwable $e) {
    echo "caught\n";
}

echo "all done!\n";

In that case I'd expect "caught" to be echo'd out and then the script to say "all done!". Instead I get this:

Notice: Undefined variable: a in C:\games\test-ssh3.php on line 12
all done!

Am I misunderstanding something?

neubert
  • 15,947
  • 24
  • 120
  • 212

1 Answers1

1

Exceptions are only thrown for certain types of errors that previously would halt execution (E_RECOVERABLE_ERROR). Warnings and notices do not halt execution therefore no exception is thrown (found a source for this).

You have to define a custom error handler and throw the exception there. PHP Notices are not exceptions so they are not caught via a try/catch block.

set_error_handler('custom_error_handler');

function custom_error_handler($severity, $message, $filename, $lineno) {
    throw new ErrorException($message, 0, $severity, $filename, $lineno);
}

try {
    echo $a[4];
} catch (ErrorException $e) {
    echo $e->getMessage().PHP_EOL;
}

echo "all done!\n";
Ricardo Velhote
  • 4,630
  • 1
  • 24
  • 30
  • That's been an option since PHP 5.0 but the docs (linked to above) say "_Instead of reporting errors through the traditional error reporting mechanism used by PHP 5, most errors are now reported by throwing Error exceptions_" so based on that it sounds like I shouldn't _have_ to do that. – neubert Feb 07 '18 at 15:26
  • 1
    Exceptions are only thrown for certain types of errors that previously would halt execution (`E_RECOVERABLE_ERROR`). Warnings and notices do not halt execution therefore no exception is thrown. – Ricardo Velhote Feb 07 '18 at 16:07