Recover Only Works in Deferred Functions

recover() returns nil because it was not called directly from a deferred function

Quick Answer

recover() must be called directly inside a deferred function to catch panics. Calling it in a regular function or in a function called by defer does not work.

Why This Happens

The recover() built-in only catches panics when called directly inside a deferred function. If you call recover() in a non-deferred function, or in a function that is called by the deferred function (indirect), it returns nil and does not catch the panic.

The Problem

func safeDiv(a, b int) (result int, err error) {
    recover() // does not work here, not in a defer
    return a / b, nil
}

The Fix

func safeDiv(a, b int) (result int, err error) {
    defer func() {
        if r := recover(); r != nil {
            err = fmt.Errorf("panic: %v", r)
        }
    }()
    return a / b, nil
}

Step-by-Step Fix

  1. 1

    Identify the misplaced recover

    Find the recover() call that is not inside a deferred function.

  2. 2

    Wrap in a deferred closure

    Move recover() inside a deferred anonymous function.

  3. 3

    Use named returns for errors

    Use named return values so the deferred function can set the error when recovering from a panic.

Bugsly catches this automatically

Bugsly's AI analyzes this error pattern in real-time, explains what went wrong in plain English, and suggests the exact fix — before your users even report it.

Try Bugsly free