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()).

Syntax

final public Exception::getPrevious()

Parameters

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.

<?php
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 {
  doStuff();
} catch(Exception $e) {
  do {
    printf("%s:%d %s (%d) [%s]\n", 
           $e->getFile(), 
           $e->getLine(), 
           $e->getMessage(), 
           $e->getCode(), 
           get_class($e));
  } 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