PHP error guide

TypeError not caught by Exception: meaning and fix

Error summary

Correct the invalid type at its boundary; if a common last-resort handler is required, catch Throwable rather than Exception.

What it means

Correct the invalid type at its boundary; if a common last-resort handler is required, catch Throwable rather than Exception.

What the error means

TypeError implements Throwable through Error, not through Exception, so a catch (Exception $e) block does not match it.

Why PHP produces it

PHP detected a type contract violation and created TypeError, while the surrounding handler only accepted the separate Exception branch of the Throwable hierarchy.

PHP version notes

The behavior described for TypeError not caught by Exception applies to PHP 7.4–8.4 unless a narrower version is stated; exact wording can vary by SAPI and patch release.

Most common causes

  • Unvalidated string input reaches a typed parameter.
  • A return value violates its declared type.
  • Legacy code assumes Exception catches engine Error objects in PHP 7+.

Minimal examples

BAD — reproduces the problem

php
try { calculate($_POST["amount"]); } catch (Exception $e) { echo "failed"; }

FIXED — safer pattern

php
if (!is_int($amount)) { throw new InvalidArgumentException("Invalid amount"); } calculate($amount);

Step-by-step diagnosis

  1. Inspect the function signature and the actual type named in the message.
  2. Use get_debug_type() at the input boundary, not after coercive transformations.
  3. Check whether the catch clause names Exception, Error, TypeError, or Throwable.

Fixes

Validate before the typed call

Convert only validated external values and reserve Throwable catches for a real process boundary.

php
$amount = filter_var($input, FILTER_VALIDATE_INT);
if ($amount === false) {
    throw new InvalidArgumentException("Amount must be an integer");
}
calculate($amount);

Common mistakes when fixing it

  • Changing the parameter type to mixed only to suppress the symptom.
  • Catching Throwable deep in business logic and continuing.
  • Assuming numeric strings always satisfy strict integer contracts.

How to prevent it

  • Validate request, database, and API values at their boundaries.
  • Use static analysis to detect incompatible calls.
  • Document whether coercive or strict typing is intended.

Web server / environment notes

cli, fpm, apache. The Throwable hierarchy is identical across SAPIs.

Tags: cli,fpm,apache

Categories