QA
Beginner LevelPHP 8+

Why should you catch Throwable instead of Exception in PHP 7+ global error handlers?

❓ Interview Prompt: Explain PHP exception hierarchy: Throwable interface, Exception vs Error, and try-catch-finally execution flow.

Since PHP 7, the error and exception hierarchy was completely redesigned:

The 'Throwable' Hierarchy:

•
Both 'Exception' (userland application exceptions) and 'Error' (fatal runtime engine errors like 'TypeError', 'ParseError', 'DivisionByZeroError') implement the root 'Throwable' interface.
•
Catching 'catch (Exception $e)' will NOT catch fatal engine errors!
•
To build a global error handler that traps both application exceptions and fatal PHP runtime errors, catch 'Throwable'.

The 'finally' Block:

The 'finally' block executes unconditionally after 'try' and 'catch' blocks, ensuring cleanup operations (closing file handles, releasing locks) run even if exceptions occur.

Code Implementation Example

php
<?php
declare(strict_types=1);

try {
    // Triggers a TypeError (Engine Error, not standard Exception!)
    $result = calculateTotal("invalid_string", 5);
} catch (Throwable $e) {
    // Catches BOTH Exception and Error instances in PHP 7+!
    error_log("Caught Throwable: " . $e->getMessage());
    echo "An unexpected error occurred.";
} finally {
    echo "
Cleanup executed successfully.";
}
💡Catching the root Throwable interface to handle both application exceptions and fatal engine errors.
🎯 Interview Key Takeaway

Catch Throwable to trap both userland Exception instances and PHP engine Error exceptions in global error handlers.

#Throwable#Exceptions#Error Handling#Beginner
Back to all PHP 8+ Questions→

More PHP 8+ Interview Questions

Beginner LevelPHP

What is PHP and how does its shared-nothing request lifecycle work?

Beginner LevelPHP

What is the difference between echo and print in PHP?

Beginner LevelPHP

What is the difference between isset(), empty(), and is_null() in PHP?