PHP 7 interview question · Most asked
Explain the `Throwable`, `Error` and `Exception` hierarchy introduced in PHP 7.
Summary
PHP 7 made most fatal errors catchable by throwing Error objects. Both Error and Exception implement the new Throwable interface, but Error does not extend Exception.
Longer Answer
Subclasses of Error include TypeError, ParseError, ArithmeticError, DivisionByZeroError and ArgumentCountError (7.1). Old catch (Exception $e) blocks don't catch them, which is intentional to preserve BC. Catch Throwable at top-level handlers. User classes can't implement Throwable directly; extend Exception instead.
Code Example
<?php
try {
intdiv(1, 0);
} catch (DivisionByZeroError $e) {
echo 'Cannot divide: ', $e->getMessage();
} catch (Throwable $e) {
error_log((string) $e);
}
Key Points
Throwable→Error,Exceptioncatch (Exception)doesn't catchError- Catch
Throwablein global handlers set_exception_handlerreceivesThrowablein 7+
Explanation
Common mistakes
- Type-hinting
Exceptionin a global error handler and missingErrors
More most-asked PHP 7 questions
- What are typed properties in PHP 7.4?
- What are arrow functions in PHP 7.4 and how do they differ from closures?
- What were the headline improvements of PHP 7.0 over PHP 5.6?
- Explain scalar type declarations and coercive vs strict mode in PHP 7.
- What are nullable types in PHP 7.1?
- How do return type declarations work in PHP 7?
- What does the null coalescing operator `??` do, and how is it different from `isset()` with a ternary?
- What are the main breaking changes when upgrading from PHP 7.4 to 8.0?