Maaz Zindani

Loading the index…

↑↓ move↵ openesc close4072 pages
Node.js, PHP and APIs

A PHP fatal error is not caught by try/catch

ErrorFatal error: Uncaught TypeError

Short answer

Two different things look like a fatal error. Most are Error objects since PHP 7, and catch (Throwable) handles them. A true E_ERROR, such as memory exhaustion, halts the script and no catch runs: log it from a function registered with register_shutdown_function() that reads error_get_last().

  • Applies to PHP 8.3, PHP 8.4
  • Updated
  • By Maaz Zindani, Senior Software Engineer

Fix it fast

  1. 1Find out which cause you have

    Read the first words of the message. If it says Uncaught followed by a class name, it is an exception object. If it is a plain Fatal error with no class, it is a halting error.

    php -d display_errors=1 script.php
  2. 2Match what you see, then jump to its fix

    1. 1Fatal error: Uncaught TypeError (or DivisionByZeroError, ValueError, ArgumentCountError)catch (Exception) misses Error, which is a different branchFix
    2. 2Fatal error: Allowed memory size exhausted, or Maximum execution time exceeded, with no Uncaught prefixA halting E_ERROR cannot be thrown or handled in the scriptFix
    3. 3Nothing is logged, or the logged error is a different, earlier oneThe shutdown function itself runs into troubleFix

What does the error look like?

  • Fatal error: Uncaught TypeError
  • Fatal error: Allowed memory size exhausted

Cause 1 of 3

catch (Exception) misses Error, which is a different branch

1Check

Error implements Throwable, just as Exception does, but it is not a subclass of Exception. TypeError, ArgumentCountError, ValueError and DivisionByZeroError are all Error classes. A catch for Exception alone never sees them.

grep -rn "catch (Exception" src/

2Fix

Catch Throwable, or name the Error class you expect, and keep the Exception handler for your own exceptions.

try {
    intdiv(1, 0);
} catch (DivisionByZeroError $e) {
    error_log('Math error: ' . $e->getMessage());
} catch (Throwable $e) {
    error_log(get_class($e) . ': ' . $e->getMessage());
}

3Verify

Run the code and confirm the message goes to the log instead of ending the script.

php test.php; echo "exit: $?"

Confirmed by php.net

Did this fix it?

Cause 2 of 3

A halting E_ERROR cannot be thrown or handled in the script

1Check

E_ERROR halts execution, and the manual says E_ERROR, E_PARSE, E_CORE_ERROR and E_COMPILE_ERROR cannot be handled by a function set with set_error_handler(). No try/catch or error handler sees them.

php -r 'ini_set("memory_limit","8M"); $a=[]; while(true){$a[]=str_repeat("x",1024*1024);}'

2Fix

Register a shutdown function. Shutdown functions still run after a fatal error, and error_get_last() returns the details, so you can log them and show a clean error page.

register_shutdown_function(function () {
    $e = error_get_last();
    if ($e !== null && in_array($e['type'], [E_ERROR, E_PARSE, E_CORE_ERROR, E_COMPILE_ERROR], true)) {
        error_log("Fatal: {$e['message']} in {$e['file']}:{$e['line']}");
    }
});

3Verify

Trigger a fatal error on purpose in a test script and check the log line.

tail -n 5 /var/log/php_errors.log

Confirmed by php.net

Did this fix it?

Cause 3 of 3

The shutdown function itself runs into trouble

1Check

If several shutdown functions are registered, an error raised in an earlier one can replace what error_get_last() returns. Under Apache the working directory can change inside a shutdown function, so relative file paths fail.

grep -rn "register_shutdown_function" src/ app/

2Fix

Register your fatal-error logger first, use absolute paths inside it, and keep it short.

register_shutdown_function(function () {
    $e = error_get_last();
    if ($e) {
        file_put_contents('/var/log/myapp/fatal.log', json_encode($e) . "\n", FILE_APPEND);
    }
});

3Verify

Force a fatal error and read the file.

tail -n 1 /var/log/myapp/fatal.log

Confirmed by php.net

Did this fix it?

How do I stop it coming back?

  • Treat a fatal error as a bug to fix (raise memory, fix the loop), not as something to hide with a handler.
  • Use catch (Throwable) at the outermost layer, such as a front controller, to return a clean error response.
  • Log fatal errors to a file or service, and keep display_errors off in production.

Sources

How was this page made?

I drafted this page with AI assistance from the official documents listed under Sources. Every cause above names the document that confirms it. I have not reproduced this fix on a machine of my own yet, so read it as documented guidance, not a test report. Found a mistake? Tell me.

Which stack is behind this page?

Projects of mine built on the same technologies:

Related fixes

Back end

Apache returns 403 when a URL contains %3F

a request like /page%3Fname=test is refused while /page?name=test works

Recent Apache httpd blocks a rewrite when the request contains an encoded question mark (%3F) and the rewritten target has a literal ?.

2 causes, each with a fix

Next step

Want this handled for good?

I look after servers, apps and releases end to end. Tell me what keeps breaking.