If you crashed a Mojo program in one of the latest nightlies, you may have noticed something: Mojo can now generate stack traces for uncaught exceptions or segmentation faults! This is a long-awaited language feature and should hopefully help with debugging failures in Mojo applications. For now, these stack traces are limited to code running on the CPU.
Because we’re cautious about the performance impact this may have, to get stack traces you’ll need to set the MOJO_ENABLE_STACK_TRACE_ON_ERROR
environment variable:
export MOJO_ENABLE_STACK_TRACE_ON_ERROR=1
Fully symbolicated stack traces also need debug symbols, and right now the only way to generate those for Mojo code is to use mojo build
with -debug-level=line-tables
or similar, then run the resulting binary:
mojo build -debug-level=full hello.mojo
./hello
If you encounter a crash without the above environment variable set, you’ll be provided instructions at the command line for how to enable symbolicated stack traces.
Additionally, you can print stack traces directly from Error
in Mojo code using get_stack_trace()
:
fn main():
try:
foo()
except e:
print("stack trace of", e)
print(String(e.get_stack_trace()))
We’ll work to improve the ergonomics of this feature over time, but this should hopefully be a significant step forward for Mojo debugging.