1. recover: why it is needed and where it works
When you write an application, you almost always want it to behave predictably: either it completes successfully or it returns a clear error. But reality is more treacherous: even if you faithfully return an error, there may still be programmer bugs in the code that lead to a panic, for example an out-of-bounds slice index. And that is where the magic begins (and a little magical thinking): recover lets you catch a panic at the application boundary and turn it into a controlled result, so the program does not get “smeared” across the console by a stack trace without explaining anything to the user.
At the same time, recover is not a replacement for proper error handling; rather, it is an emergency safety cushion: it does not make bugs “not bugs”, it makes the crash manageable.
An important frame to keep in mind: if an error is expected and can be checked in advance, it is an error. If something “impossible” happens (or you forgot to check), a panic may occur. Ideally, you do not place recover everywhere, but exactly in one place where the application decides: “Okay, whatever happens inside, I will return a neat error to the outside.”
Where recover really works
recover is a capricious but honest thing: it works only in a very specific form. The rule is: recover() makes sense only inside a deferred function. During normal execution, recover() returns nil and catches nothing.
Let us see that in mini examples.
First, the version that “does not work”:
package main
import "fmt"
func main() {
fmt.Println(recover()) // <nil>
panic("boom")
}
Here, recover() is called “normally”, not through defer, so it does not save anyone.
Now the working template — the canonical skeleton:
package main
import "fmt"
func main() {
defer func() {
if r := recover(); r != nil {
fmt.Println("recovered:", r) // recovered: boom
}
}()
panic("boom")
}
Why does this work? Because when a panic occurs, Go starts “unwinding the stack”, leaving functions upward, and along the way it executes all defers. At that moment, the deferred function manages to call recover(), grab the “panic value”, and stop the avalanche.
Another subtle point that often confuses beginners: recover does not continue execution from the “panic site”. Code after the line where the panic happened will not run. recover merely turns the emergency exit into a normal return from the function where the defer was placed.
2. Safe main: one protective boundary
If you embed recover into every function, the code quickly turns into a “pie of hacks”, where every error is hidden, and then for weeks you keep asking why the application “sometimes behaves strangely”. That is why in Go people like the pattern that can be called safe main: recover sits at the top level, while the main code works with the normal (T, error) contract.
The skeleton looks like this:
package main
import "fmt"
func main() {
if err := safeRun(); err != nil {
fmt.Println("app error:", err) // app error: ...
}
}
Pay attention: our main is as “simple-minded” as possible (in a good way). It just starts the work and prints the problem. No “smart decisions” in main, otherwise later you will not understand where the application logic is and where the startup logic is.
The safeRun skeleton
Now we write safeRun, which is the boundary:
package main
import "fmt"
func safeRun() (err error) {
defer func() {
if r := recover(); r != nil {
err = fmt.Errorf("unexpected panic: %v", r)
}
}()
return run()
}
Here it is important that safeRun returns a named err error. This lets the deferred function assign err = ... right before returning. This trick is the standard way to “intervene” in a function result through defer.
And the business function run lives in the world of “normal people”:
package main
import "errors"
func run() error {
return errors.New("not implemented yet")
}
The idea is simple: if a panic occurs inside run() and everything it calls, we do not let it kill the process “dirtyly”; instead, we turn it into a clear error at the boundary. At the same time, we do not pretend that everything is fine: the error still propagates upward.
A small diagram to fit it in your head:
flowchart TD
A[main] --> B[safeRun: defer recover]
B --> C[run: business logic]
C -->|panic| D[stack unwinding]
D --> E[defer in safeRun]
E -->|recover| F[returned error]
F --> A
The point is that recover is not a “try/catch”, but an “emergency switch” on the control panel that stands at the apartment entrance, not in every room.
The meaning of panic: panic value, and how to turn it into error
A panic in Go is not necessarily a string. You can pass any value to panic(...), and it will arrive in recover() as any. That is why it is useful to know how to turn r into a clear error without losing the meaning.
Let us make a small helper. It will be useful in the application and will make safeRun cleaner.
package main
import "fmt"
func panicToError(r any) error {
if e, ok := r.(error); ok {
return fmt.Errorf("panic: %w", e)
}
return fmt.Errorf("panic: %v", r)
}
There are two cases here:
| What was passed to panic(...) | What comes to recover() | What we do |
|---|---|---|
|
|
wrap with to preserve the chain |
or |
|
format with |
Now safeRun can be made a little neater:
package main
func safeRun() (err error) {
defer func() {
if r := recover(); r != nil {
err = panicToError(r)
}
}()
return run()
}
Why is it important to distinguish error from “something else”? Because if the panic carries an error, sometimes you can later, at a higher level, recognize the error type through errors.Is/errors.As, if it was wrapped correctly. But remember: if you have a panic with an error, it is still an emergency, not a “normal branch”. Just an emergency with useful information.
3. Practical example: a mini application, “task list”
To keep recover from remaining a magic spell, let us embed it in a small application that we can continue developing later. Let it be a very modest task list that can read a command and print something.
The idea: we have a list of tasks, and the show <i> command prints a task by index. If the index is wrong, there will be a "index out of range" panic. This is the classic slice bug that we have already met at this stage of learning.
run: read the command and pass control to the handler
Let us make run() read a command and execute it:
package main
import (
"fmt"
)
func run() error {
tasks := []string{"learn_go", "drink_tea"}
var cmd string
fmt.Scan(&cmd)
return handle(cmd, tasks)
}
handle: version without checks, so we can see the panic
Now implement handle. We will intentionally make a version without checks so that we can see the panic:
package main
import "fmt"
func handle(cmd string, tasks []string) error {
if cmd == "show" {
var i int
fmt.Scan(&i)
fmt.Println(tasks[i]) // if i=10, panic will occur
return nil
}
fmt.Println("unknown command") // unknown command
return nil
}
Assembling safe main as a whole
Now let us assemble safe main as a whole:
package main
import "fmt"
func main() {
if err := safeRun(); err != nil {
fmt.Println("app error:", err)
}
}
If you run it with the input:
show 10
then without recover the program will crash with a panic. But with safeRun you will get controlled output like this:
app error: panic: runtime error: index out of range [10] with length 2
Yes, the message is still “developer-facing”, but the main thing is that the application did not suddenly tear open the user's console with a crash, and now you can decide how exactly to present such errors. Ideally, you would show the user something friendlier and leave the details for diagnostics. But we have already built the boundary mechanism itself.
4. Should you print the stack when recovering
When you catch a panic, the temptation appears: “Oh! Caught it! Now I will pretend nothing happened and continue.” That is a bad scenario, because the panic may have happened at a moment when part of the data had already changed, and the program state became questionable. Therefore, the typical result after recover is to stop the current operation and return an error upward.
Sometimes you also want to get a stack trace. By default, when a panic is not intercepted, Go prints it itself. If you catch the panic, you “cancelled” the standard panic output, and the stack will no longer be printed automatically. That can be useful, but be careful: printing the stack “in the user's face” is a dubious idea.
If you still need it, for example during development, you can take the stack from runtime/debug. There is no need to deeply understand the format here — it is enough to know that such an option exists.
package main
import (
"fmt"
"runtime/debug"
)
func safeRun() (err error) {
defer func() {
if r := recover(); r != nil {
fmt.Printf("panic stack:\n%s\n", debug.Stack())
err = panicToError(r)
}
}()
return run()
}
There is an important philosophical detail here: recover should not turn into a “vacuum cleaner that sucks in all the problems”. If you caught a panic, you made the crash predictable, but after that you still need to fix the cause. Otherwise it will be like putting a bandage on a fire alarm because it “beeps too loudly”.
5. Typical mistakes when using recover
Mistake #1: calling recover() outside a deferred function and waiting for a miracle.
recover is not a “universal trap”. In a normal place it returns nil and catches nothing, because interception is possible only during stack unwinding when defers are being executed.
Mistake #2: putting recover into every function “so it does not crash”.
That turns bugs into hidden bugs: the program seems not to crash, but it may continue working in a dubious state. It is much healthier to keep one protective boundary, for example safeRun, and fix the cause of the panic in the logic.
Mistake #3: catching a panic and staying silent.
If after recover you return nothing and report nothing, you create the effect of an “vanishing error”: the application behaves strangely, but it is impossible to understand why. After catching a panic, there must be an explicit action: return an error, print a clear message, terminate the operation.
Mistake #4: trying to continue execution after recover as if nothing had happened.
recover does not take you back “to the line after the panic”. It merely allows the function to finish normally. Therefore, the correct strategy is to end the current scenario, return an error upward, and not pretend that everything is fine.
Mistake #5: using panic/recover instead of an ordinary error for expected situations.
If you can check a condition in advance, for example the index must be within range, the divisor is not zero, the key exists in the map, then this is an ordinary logic branch, and it belongs in if and return error, not in panic. Panics are for violated assumptions and programmer errors, and recover is a rare safety net at the application boundary.
GO TO FULL VERSION