PHP Tutorial PHP Advanced PHP References

PHP Exception - getPrevious() Method

The PHP Exception::getPrevious() method returns previous Throwable (which had been passed as the third parameter of Exception::__construct()).


final public Exception::getPrevious()


No parameter is required.

Return Value

Returns the previous Throwable if available or null otherwise.

Example: Exception::getPrevious() example

The example below shows the usage of Exception::getPrevious() method.

class MyCustomException extends Exception {}

function doStuff() {
  try {
    throw new InvalidArgumentException("You are doing it wrong!", 112);
  } catch(Exception $e) {
    throw new MyCustomException("Something happened", 911, $e);

try {
} catch(Exception $e) {
  do {
    printf("%s:%d %s (%d) [%s]\n", 
  } while($e = $e->getPrevious());

The output of the above code will be:

Main.php:8 Something happened (911) [MyCustomException]
Main.php:6 You are doing it wrong! (112) [InvalidArgumentException]

❮ PHP - Exceptions