Stack trace
- Dart course
- Intermediate
- Lesson 102/116
- 5 min
Learn stack trace and debugging.
Stack trace
When an exception is thrown Dart records the current call stack. This is called a stack trace.
It is captured as the second parameter in a catch block: try { ... } catch (e, s) { print(s); }. Here s is a StackTrace object.
The stack trace shows where the error originated (file, line, function). It is the main debugging tool; in production it is sent to logging tools.
A stack trace example
Typical usage: try { riskyOperation(); } catch (e, s) { print('Error: $e'); print(s); }.
s is a StackTrace object; it is turned into text with toString(). print(s) does this automatically.
In development you print it; in production you send it to a logging service. Without a stack trace an error stays mysterious.
Practice Catch the error and the trace
Write void risky() { throw StateError('bad state'); }. In main call it with try { risky(); } catch (e, s) { print(e); }. The second parameter s of catch (e, s) is the StackTrace; here we print e.
Starter code
// Define the risky function
void main() {
// call risky() and catch the error
}Sample solution
void risky() {
throw StateError('bad state');
}
void main() {
try {
risky();
} catch (e, s) {
print(e);
}
}Expected output
Bad state: bad state
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Stack trace parts
| Term | Meaning |
|---|---|
catch (e, s) |
Captures StackTrace |
s |
StackTrace variable |
print(s) |
Prints the trace |
throw |
Throws the exception |
2 How is a StackTrace captured in a catch block?
- catch (e, s) Correct answer
- catch (s, e)
- catch (e)
- catch (s)
Explanation: catch (e, s) takes the StackTrace as the second parameter.
3 StackTrace parameter
try { risky(); } catch (e, ____) { print(s); }
try { risky(); } catch (e, s) { print(s); }
Explanation: the second parameter s is the StackTrace.