Panic in Go
Start with Panic in Go
A panic interrupts normal execution and begins stack unwinding. It is not the ordinary mechanism for reporting expected input failures.
What you’ll learn
- Explain the main purpose of panic in go.
- Read and run the complete Go example in this lesson.
- Apply the concept and recognize common mistakes.
Understand the idea
The built-in panic(value) stops the current normal flow, runs deferred calls while unwinding, and terminates the goroutine if not recovered appropriately. Many runtime failures, such as an out-of-bounds index, can also panic.
The example catches a deliberate panic so the overall example remains runnable. In real applications, prefer error returns for expected problems; use panic sparingly for truly exceptional situations or violated internal invariants.
Visualize how it works
Follow this diagram before executing the example. Check where a value or decision changes what runs next.
Run a complete Go example
This example is a complete program. Save it as main.go or paste it into the Go Playground.
Go code
package main
import "fmt"
func demo() {
defer func() {
if value := recover(); value != nil {
fmt.Println("Recovered:", value)
}
}()
fmt.Println("Before panic")
panic("unexpected state")
}
func main() {
demo()
fmt.Println("After demo")
}
Output
Before panic
Recovered: unexpected state
After demoTrace what the program does
demo prints Before panic then panics. The deferred closure runs during stack unwinding and recovers the panic. Execution returns to the caller of demo, so main prints After demo.
Avoid common mistakes
- A recovered panic does not resume executing after the panic statement.
- Use ordinary error returns for validation failures and other expected conditions.
Try it yourself
Add a deferred print statement before the recovery defer and predict the last-in-first-out order in which deferred calls run.
Tip: Edit the example above, predict the output, and run the modified code to test your reasoning.
Check your understanding
What you should remember
You have practiced Panic in Go in a small, self-contained program. The important habit is to predict what runs, inspect the actual output and distinguish the language rule from the particular example.
Before continuing, make sure you can explain the program to someone who has not seen it, including the line that changes its result.
Reaching the recap and completing the quizzes are separate milestones.