A PHP fatal error is not caught by try/catch
Fatal error: Uncaught TypeErrorShort 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().
Fix it fast
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.php2Match what you see, then jump to its fix
- 1
Fatal error: Uncaught TypeError (or DivisionByZeroError, ValueError, ArgumentCountError)catch (Exception) misses Error, which is a different branchFix - 2
Fatal 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
Nothing is logged, or the logged error is a different, earlier oneThe shutdown function itself runs into troubleFix
- 1
What does the error look like?
Fatal error: Uncaught TypeErrorFatal 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
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.logConfirmed by php.net
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.logConfirmed by php.net
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
Android gets HTML instead of JSON from a PHP API
org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONObject
The response body is not JSON.
2 causes, each with a fixBack 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 fixBack end
Apache returns 500 with Premature end of script headers
500 Internal Server Error
Apache ran your script, but the script printed no valid HTTP header before its output.
3 causes, each with a fixBack end
Apache returns 503 or 504 because PHP-FPM did not answer in time
Error dispatching request
Apache sent the request to PHP-FPM and gave up waiting.
3 causes, each with a fixBack end
AWS SDK for PHP cannot get credentials from the instance profile metadata server
Error retrieving credentials from the instance profile metadata server.
The SDK tries the EC2 instance metadata service when it has no valid credentials from anywhere earlier in its chain.
4 causes, each with a fixBack end
AWS SDK for PHP rejects requests: the signature is from the future
Signature not yet current: {date} is still later than {date}
AWS compares the timestamp in your signed request with its own clock.
2 causes, each with a fix