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, Exception
  • catch (Exception) doesn't catch Error
  • Catch Throwable in global handlers
  • set_exception_handler receives Throwable in 7+

Explanation

Common mistakes

  • Type-hinting Exception in a global error handler and missing Errors

More most-asked PHP 7 questions

← All PHP 7 questions