Maaz Zindani

Loading the index…

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

A PHP try/catch block runs but the catch never fires

ErrorFatal error: Uncaught TypeError

Short answer

A catch block only receives thrown objects of the type it names. Three things get past catch (Exception): a warning or notice, which is not thrown at all; an Error such as TypeError, which does not extend Exception; and a bare Exception name inside a namespace, which points at the wrong class.

  • 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 line of what PHP printed. 'Warning' or 'Notice' means nothing was thrown. 'Fatal error: Uncaught' names the class that was thrown: compare it to the class in your catch.

    php -r 'try { intdiv(1, 0); } catch (Exception $e) { echo "caught"; }'
  2. 2Match what you see, then jump to its fix

    1. 1The output starts with Warning: or Notice: and the script keeps runningIt is a warning or notice, not an exceptionFix
    2. 2Fatal error: Uncaught TypeError, DivisionByZeroError, ValueError or ArgumentCountErrorAn Error was thrown and you only catch ExceptionFix
    3. 3Uncaught Exception even though the catch says Exception, and the file starts with namespace App\...;Inside a namespace, Exception means a different classFix

What does the error look like?

  • Fatal error: Uncaught TypeError

Cause 1 of 3

It is a warning or notice, not an exception

1Check

Many older functions report problems as errors and return false or null instead of throwing. A try block cannot catch what was never thrown.

$r = file_get_contents('/no/such/file');
var_dump($r);   // bool(false) plus a warning, no exception

2Fix

Check the return value, or turn errors into ErrorException with set_error_handler, as the manual shows. Skip deprecations in the handler so new ones do not break the app.

set_error_handler(function (int $no, string $str, string $file, int $line) {
    if (!(error_reporting() & $no)) { return; }
    if ($no === E_DEPRECATED || $no === E_USER_DEPRECATED) { return; }
    throw new ErrorException($str, 0, $no, $file, $line);
});

3Verify

Run the failing call again. It now lands in the catch block.

try { file_get_contents('/no/such/file'); } catch (ErrorException $e) { echo "caught"; }

Confirmed by php.net

Did this fix it?

Cause 2 of 3

An Error was thrown and you only catch Exception

1Check

Error and Exception are separate classes. Both implement Throwable, so catch (Exception) does not catch TypeError or other Error subclasses.

php -r 'try { strlen([]); } catch (Exception $e) { echo "caught"; }'

2Fix

Catch the specific class you expect, or Throwable when you must handle both. Errors usually point at a bug, so log them and fix the code rather than hide them.

try {
    doWork();
} catch (TypeError $e) {
    error_log($e->getMessage());
} catch (Exception $e) {
    error_log($e->getMessage());
}

3Verify

Trigger the error in a test. The matching catch runs.

php -r 'try { strlen([]); } catch (Throwable $e) { echo get_class($e); }'

Confirmed by php.net

Did this fix it?

Cause 3 of 3

Inside a namespace, Exception means a different class

1Check

In a namespaced file a class name without a leading backslash is looked up in the current namespace. catch (Exception) then names App\Exception, which never gets thrown, so the real one passes by.

grep -n "^namespace\|^use \|catch (" src/Service.php

2Fix

Write \Exception with a leading backslash, or import it with use Exception;.

namespace App\Services;

use Exception;

try {
    run();
} catch (Exception $e) {
    // now the global class
}

3Verify

Run the code path that throws. The catch block runs.

php artisan tinker   # or your own entry point

Confirmed by php.net

Did this fix it?

How do I stop it coming back?

  • Use a catch for the specific class you expect instead of the broadest one.
  • Convert warnings to ErrorException in one place, such as the bootstrap file.
  • Import global classes with use at the top of every namespaced file.

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.