Exercise 13: Java-Style Stack Traces - Reformatting Go Panics
Want to learn more? Read Stacktraces on Internals for Interns for a deep dive into how Go generates panic stack traces.
In this exercise, you’ll modify Go’s panic output to look like Java’s exception format. You’ll learn how Go generates stack traces, where the panic header is printed, and how individual stack frames are formatted — then rewrite all of it.
Learning Objectives
By the end of this exercise, you will:
- Understand how Go formats stack traces in the runtime
- Know where panic messages are generated in
panic.go - Understand how
traceback.goformats individual stack frames - Modify runtime output formatting to produce a different style
Introduction: Panic and Defer Internals
How panic Works
When you call panic(v), the Go runtime:
- Stores the panic value in the current goroutine’s
_paniclinked list - Begins unwinding the stack: runs all deferred functions in LIFO order
- If a
defercallsrecover(), the panic is stopped and execution continues normally - If no
recover()is called, the runtime prints the panic header and stack trace, then exits
How defer Works
Deferred function calls are stored in the goroutine’s _defer linked list. Each defer statement at compile time becomes a deferproc() call that prepends to this list. When a function returns (normally or via panic), deferreturn() or gopanic() works through the list in reverse order.
The key interaction: defer recover() only stops a panic if the recover() call is directly within a deferred function (not nested further). This is enforced by the runtime checking whether the goroutine currently has an active panic.
Stack Trace Format
Go’s current stack trace format:
panic: Something went wrong
goroutine 1 [running]:
main.methodC(...)
/home/user/project/main.go:15 +0x45
main.methodB(...)
/home/user/project/main.go:11 +0x23
main.methodA(...)
/home/user/project/main.go:7 +0x12
main.main()
/home/user/project/main.go:19 +0x67
exit status 2
Java’s stack trace format:
Exception in thread "main" go.runtime.Panic: Something went wrong
at main.methodC(main.go:15)
at main.methodB(main.go:11)
at main.methodA(main.go:7)
at main.main(main.go:19)
We’ll transform Go’s output into Java’s format.
Step 1: Create a Test Program
Create stack_trace_demo.go:
package main
import "fmt"
func methodC() {
panic("Something went wrong")
}
func methodB() {
methodC()
}
func methodA() {
methodB()
}
func main() {
fmt.Println("Starting the program...")
methodA()
}
Run with standard Go to see the current format:
go run stack_trace_demo.go
Current output:
Starting the program...
panic: Something went wrong
goroutine 1 [running]:
main.methodC(...)
/home/user/project/stack_trace_demo.go:6 +0x27
main.methodB(...)
/home/user/project/stack_trace_demo.go:10 +0x17
main.methodA(...)
/home/user/project/stack_trace_demo.go:14 +0x17
main.main()
/home/user/project/stack_trace_demo.go:19 +0x6e
exit status 2
Step 2: Navigate to the Runtime Files
cd go/src/runtime
We’ll modify two files:
- panic.go — The panic header message (panic: ...)
- traceback.go — Individual stack frame formatting
Step 3: Modify the Panic Header
Edit go/src/runtime/panic.go:
Find the printpanics function:
grep -n "func printpanics" go/src/runtime/panic.go
Inside printpanics, look for where "panic: " is printed. You’ll find a section like:
print("panic: ")
printpanicval(p.arg)
Change the prefix to match Java’s format:
print("Exception in thread \"main\" go.runtime.Panic: ")
printpanicval(p.arg)
This changes the first line of the panic output from panic: Something went wrong to Exception in thread "main" go.runtime.Panic: Something went wrong.
Step 4: Remove the Goroutine Header
Edit go/src/runtime/traceback.go:
Find the goroutineheader function:
grep -n "func goroutineheader" go/src/runtime/traceback.go
This function prints the goroutine 1 [running]: line that appears between the panic message and the stack frames. Add an early return at the top to suppress it:
func goroutineheader(gp *g) {
return // Skip goroutine info — Java doesn't have this
level, _, _ := gotraceback()
// ... rest of original code is now unreachable
}
Note on the blank line: Even after suppressing
goroutineheader, a blank line will still appear between the panic header and the first frame. It comes fromdopanic_minpanic.go(around line 1583), which callsprint("\n")immediately beforegoroutineheader. If you want to eliminate it, also find thatprint("\n")indopanic_mand remove it. The exercise’s Java-style output works correctly either way — the blank line is a minor cosmetic detail.
Step 5: Transform Stack Frame Formatting
Still in go/src/runtime/traceback.go:
Find the traceback2 function:
grep -n "func traceback2" go/src/runtime/traceback.go
Inside traceback2, comment out the gotraceback() call near the top of the function body (around line 966 — the exact location varies). Look for:
level, _, _ := gotraceback()
Comment it out:
// level, _, _ := gotraceback() // not needed for Java-style output
Now find where each stack frame is printed. Look for the section that calls printFuncName and prints the file and line number. It looks approximately like:
printFuncName(name)
print("(")
if iu.isInlined(uf) {
print("...")
} else {
argp := unsafe.Pointer(u.frame.argp)
printArgs(f, argp, u.symPC())
}
print(")\n")
print("\t", file, ":", line)
if !iu.isInlined(uf) {
if u.frame.pc > f.entry() {
print(" +", hex(u.frame.pc-f.entry()))
}
if gp.m != nil && gp.m.throwing >= throwTypeRuntime && gp == gp.m.curg || level >= 2 {
print(" fp=", hex(u.frame.fp), " sp=", hex(u.frame.sp), " pc=", hex(u.frame.pc))
}
}
print("\n")
Replace this entire block with Java-style frame printing:
// Extract just the filename (not the full path)
fileName := file
for i := len(file) - 1; i >= 0; i-- {
if file[i] == '/' || file[i] == '\\' {
fileName = file[i+1:]
break
}
}
print(" at ", name, "(", fileName, ":", line, ")\n")
Understanding the Changes
name— The fully qualified function name (e.g.,main.methodC)file— The full file path (e.g.,/home/user/project/stack_trace_demo.go)line— The line number- The loop extracts just the filename from the full path, matching Java’s
ClassName.javaconvention " at "— Java uses 4-space indent (not a tab) beforeat- We drop the hex offset (
+0x45), frame pointer, and stack pointer — Java doesn’t show these
Step 6: Rebuild the Go Toolchain
cd ../ # back to go/src
./make.bash
Step 7: Test Java-Style Stack Traces
../go/bin/go run stack_trace_demo.go
Expected output:
Starting the program...
Exception in thread "main" go.runtime.Panic: Something went wrong
at main.methodC(stack_trace_demo.go:6)
at main.methodB(stack_trace_demo.go:10)
at main.methodA(stack_trace_demo.go:14)
at main.main(stack_trace_demo.go:19)
exit status 2
The output now looks like Java’s Exception in thread "main" java.lang.RuntimeException: ... format.
Step 8: Test with recover()
Verify that recover() still works correctly — our changes only affect formatting, not panic/recover semantics:
package main
import "fmt"
func riskyOperation() {
panic("oh no!")
}
func safeWrapper() {
defer func() {
if r := recover(); r != nil {
fmt.Println("Recovered from panic:", r)
}
}()
riskyOperation()
}
func main() {
fmt.Println("Before risky operation")
safeWrapper()
fmt.Println("After risky operation — we recovered!")
}
../go/bin/go run recover_demo.go
Expected output:
Before risky operation
Recovered from panic: oh no!
After risky operation — we recovered!
The panic/recover mechanism is completely unaffected — we only changed how unrecovered panics are displayed.
Step 9: Compare a Deeper Stack
Test with a more complex call stack to see the format handles multiple levels:
package main
func level5() { panic("deep panic") }
func level4() { level5() }
func level3() { level4() }
func level2() { level3() }
func level1() { level2() }
func main() { level1() }
../go/bin/go run deep_panic.go
Expected output:
Exception in thread "main" go.runtime.Panic: deep panic
at main.level5(deep_panic.go:3)
at main.level4(deep_panic.go:4)
at main.level3(deep_panic.go:5)
at main.level2(deep_panic.go:6)
at main.level1(deep_panic.go:7)
at main.main(deep_panic.go:8)
exit status 2
Each frame is cleanly formatted on one line, with no hex offsets or frame pointers — exactly matching Java’s style.
Cleanup
To restore Go’s original stack trace format:
cd go/src/runtime
git checkout panic.go traceback.go
cd ..
./make.bash
Summary
You’ve transformed Go’s stack traces into Java-style exception output:
Before: Go style — technical, verbose, includes offsets and full paths
goroutine 1 [running]:
main.methodC(...)
/full/path/to/main.go:6 +0x27
After: Java style — clean, familiar, filename only
Exception in thread "main" go.runtime.Panic: Something went wrong
at main.methodC(main.go:6)
Changes: runtime/panic.go — printpanics() header text
runtime/traceback.go — goroutineheader() suppressed
— traceback2() frame format replaced
Result: Go panics now look like Java exceptions
This exercise revealed the three-layer structure of Go’s panic output: the panic value header, the goroutine context header, and the per-frame trace — each printed by a separate function that you can modify independently.
Congratulations on completing all workshop exercises! Return to the main workshop