getTrace()
Learn how PHP's Exception::getTrace() returns the stack trace as an array, what each frame contains, and how it differs from getTraceAsString().
PHP getTrace()
Exception::getTrace() returns the stack trace of an exception as an array. Each element describes one function or method call that was on the call stack at the moment the exception was thrown, ordered from the throw point outward. It is one of the most useful tools for figuring out where and how an error happened.
This page covers what getTrace() returns, the structure of each trace frame, and how it differs from the more familiar getTraceAsString(). The method is defined on the base Throwable interface, so it is available on every Exception and Error object.
public Exception::getTrace(): arrayIt takes no arguments and returns an indexed array. Frame 0 is the innermost call (the function that actually threw), and the indexes grow toward the outermost caller.
Quick example
The following script throws from a nested call and prints each frame of the trace:
<?php
function readConfig($path) {
return parseFile($path);
}
function parseFile($path) {
throw new Exception("Cannot read file: $path");
}
try {
readConfig('/etc/app.conf');
} catch (Exception $e) {
$trace = $e->getTrace();
echo "Number of frames: " . count($trace) . "\n";
foreach ($trace as $i => $frame) {
echo "#$i {$frame['function']}() called in {$frame['file']} on line {$frame['line']}\n";
}
}Output:
Number of frames: 2
#0 parseFile() called in /path/to/script.php on line 4
#1 readConfig() called in /path/to/script.php on line 12Notice that the frame for the function that threw (parseFile) reports the line where it was called (line 4, inside readConfig), not the line of the throw itself. The throw line is available separately via getLine() and getFile().
What each trace frame contains
Each frame is an associative array. The most useful keys are:
| Key | Description |
|---|---|
function | Name of the function or method that was called. |
line | Line in file where the call was made. |
file | File where the call was made. |
class | Class name (only for method calls). |
type | -> for instance calls, :: for static calls. |
args | Array of arguments passed to the call. |
This script inspects a single frame in full:
<?php
function divide($a, $b) {
if ($b === 0) {
throw new InvalidArgumentException('Division by zero');
}
return $a / $b;
}
try {
divide(10, 0);
} catch (Exception $e) {
print_r($e->getTrace()[0]);
}Output:
Array
(
[file] => /path/to/script.php
[line] => 11
[function] => divide
[args] => Array
(
[0] => 10
[1] => 0
)
)Security note: the
argsentry contains the actual argument values, which may include passwords, tokens or other secrets. Never expose a rawgetTrace()array to end users — log it server-side instead. PHP'szend.exception_ignore_argsINI setting (on by default since PHP 7.4) stripsargsto avoid leaking sensitive data; if you do not see anargskey, that is why.
getTrace() vs getTraceAsString()
getTrace() gives you the raw array so you can format, filter, or serialize it however you like. If you just want a human-readable string, use getTraceAsString() instead, which returns the same information pre-formatted:
<?php
try {
throw new RuntimeException('Something broke');
} catch (Throwable $e) {
echo $e->getTraceAsString();
}Use the array form when you want to walk frames programmatically (e.g. build a custom error report or send structured data to a logging service), and the string form for quick display or log lines.
Where getTrace() fits in the exception API
getTrace() is one of several read-only accessors on every exception. They are most powerful when used together inside a catch block:
getMessage()— the human-readable error message.getCode()— the numeric error code.getFile()andgetLine()— where the exception was thrown.getTraceAsString()— the trace as a string.getPrevious()— the chained exception, if any.
For the broader picture of throwing and catching, see throw, try, and the Exception class.
Best Practices for Exception Handling in PHP
To ensure that your code is maintainable and easy to debug, it's important to follow best practices when handling exceptions in PHP. Here are some tips to keep in mind:
1. Use meaningful exception messages.
When throwing an exception, make sure that the message is informative and helpful. It should explain what went wrong and how to fix it. For example:
<?php
if ($someCondition) {
throw new Exception('Invalid input: the email address is not valid.');
}2. Catch only the exceptions you can handle.
When catching exceptions, it's important to catch only the exceptions that you can handle. If you catch an exception that you can't handle, you may end up hiding the real problem and making it harder to debug. For example:
<?php
try {
// Some code that may throw an exception.
} catch (InvalidArgumentException $e) {
// Handle the invalid argument exception.
} catch (Exception $e) {
// Handle all other exceptions.
}3. Log exceptions.
Logging exceptions can help you diagnose problems and troubleshoot issues. It's a good idea to log exceptions to a file or database so that you can review them later. For example:
<?php
try {
// Some code that may throw an exception.
} catch (Exception $e) {
error_log($e->getMessage(), 0);
}4. Use exception hierarchies.
Using exception hierarchies can help you organize your code and make it easier to catch specific types of exceptions. For example, you might create a DatabaseException class that extends the Exception class, and then throw that exception when a database error occurs. You could then catch only DatabaseException instances when handling database errors.
Conclusion
Exception handling is a critical aspect of PHP programming, and the getTrace() method is a valuable tool for debugging and troubleshooting exceptions. By returning a backtrace of the execution context, you can pinpoint where an exception occurred and how it was triggered.
In this guide, we've covered the basics of exception handling in PHP, including how to throw and catch exceptions, and best practices for using exceptions effectively. We've also explored the getTrace() method and how it can help you diagnose and fix errors in your code.
By following these best practices and leveraging the getTrace() method, you can write PHP code that is robust, reliable, and easy to maintain. Exception handling may seem like a small detail, but it can make a big difference in the quality and usability of your code.