PHP Throwable interface

In PHP 7, the Throwable interface serves as the base interface for any object that can be thrown using the throw statement, including Error and Exception. Both Error and Exception classes implement this interface, making it possible to catch all throwable objects uniformly.

Syntax

Throwable {
    /* Methods */
    abstract public getMessage ( void ) : string
    abstract public getCode ( void ) : int
    abstract public getFile ( void ) : string
    abstract public getLine ( void ) : int
    abstract public getTrace ( void ) : array
    abstract public getTraceAsString ( void ) : string
    abstract public getPrevious ( void ) : Throwable
    abstract public __toString ( void ) : string
}

Methods

Method Return Type Description
getMessage() string Returns the message associated with the thrown object
getCode() int Returns the error code associated with the thrown object
getFile() string Get the name of the file where the thrown object was created
getLine() int Returns the line number where the thrown object was instantiated
getTrace() array Returns the stack trace as an array
getTraceAsString() string Returns the stack trace as a string
getPrevious() Throwable Returns any previous Throwable object
__toString() string Gets a string representation of the thrown object

Example

Here's how you can catch both exceptions and errors using the Throwable interface −

<?php
try {
    // This will throw a TypeError (which implements Throwable)
    $result = 10 / "hello";
} catch (Throwable $t) {
    echo "Caught: " . $t->getMessage() . "<br>";
    echo "File: " . $t->getFile() . "<br>";
    echo "Line: " . $t->getLine() . "<br>";
    echo "Code: " . $t->getCode() . "<br>";
}

// Example with custom exception
try {
    throw new Exception("Custom exception message", 100);
} catch (Throwable $t) {
    echo "\nSecond catch:<br>";
    echo "Message: " . $t->getMessage() . "<br>";
    echo "Code: " . $t->getCode() . "<br>";
}
?>
Caught: Unsupported operand types: int / string
File: /path/to/file.php
Line: 4
Code: 0

Second catch:
Message: Custom exception message
Code: 100

Conclusion

The Throwable interface provides a unified way to handle both exceptions and errors in PHP 7+. By catching Throwable objects, you can handle all types of errors and exceptions with a single catch block, making error handling more consistent and comprehensive.

Updated on: 2026-03-15T09:25:14+05:30

594 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements