W3docs

Try/Catch block in PHP not catching Exception

There could be several reasons why a try/catch block in PHP is not catching an exception.

There could be several reasons why a try/catch block in PHP is not catching an exception. Some common reasons include:

  1. The exception is not being thrown: Make sure the code actually triggers an exception.

    try {
        echo "No exception here";
    } catch (Exception $e) {
        echo "Caught"; // This will not run
    }
  2. The exception type is incorrect: PHP requires the caught type to match (or be a parent of) the thrown type.

    try {
        throw new RuntimeException("Runtime error");
    } catch (InvalidArgumentException $e) { // Type mismatch
        echo "Caught"; // This will not run
    }
  3. The exception is thrown outside the try block: The exception must be thrown within the try block to be caught.

    try {
        echo "Inside try";
    } catch (Exception $e) {
        echo "Caught";
    }
    throw new Exception("Outside"); // Not caught by the block above
  4. The exception is caught by a different catch block: Nested try/catch structures or outer blocks may intercept it first.

    try {
        try {
            throw new Exception("Inner");
        } catch (RuntimeException $e) { // Type mismatch
            echo "Inner caught";
        }
    } catch (Exception $e) { // Outer block catches it
        echo "Outer caught";
    }
  5. The exception is caught but not handled properly: An empty catch block or missing output/log can make it appear uncaught.

    try {
        throw new Exception("Error");
    } catch (Exception $e) {
        // Empty block or missing echo/log
        // Script continues silently
    }
  6. The exception is rethrown: If you rethrow the exception, it will propagate to an outer handler or terminate the script.

    try {
        throw new Exception("Error");
    } catch (Exception $e) {
        throw $e; // Propagates outward
    }

PHP 7+ Specifics In PHP 7 and later, Exception implements the Throwable interface. If you are catching Error types (like TypeError or ParseError), you must catch Throwable or a parent class.

try {
    throw new TypeError("Type mismatch");
} catch (Throwable $e) {
    echo "Caught: " . $e->getMessage();
}

Additionally, uncaught exceptions can be intercepted globally using set_exception_handler():

set_exception_handler(function (Throwable $e) {
    error_log($e->getMessage());
});

It's important to check the error logs and debug the issue. Verify the exact error message and exception type to understand what is happening.