PHP Tutorial PHP Advanced PHP References

PHP Exception - getTraceAsString() Method



The PHP Exception::getTraceAsString() method is used to get the Exception stack trace as a string.

Syntax

final public Exception::getTraceAsString()

Parameters

No parameter is required.

Return Value

Returns the Exception stack trace as a string.

Example: Exception::getTraceAsString() example

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

<?php
function divide($dividend, $divisor) {
  if($divisor == 0) {
    throw new Exception("Division by zero is invalid.", 25);
  }
  return $dividend / $divisor;
}

try {
  echo divide(25, 0);
} catch(Exception $e) {
  $trace = $e->getTraceAsString();
  echo $trace;
}
?>

The output of the above code will be similar to:

#0 Main.php(10): divide()
#1 {main}

❮ PHP - Exceptions

5