Skip to content

spec: recover() in nested defer #23531

Description

@guangda-hu

What version of Go are you using (go version)?

Go playground

What did you do?

package main

import (
	"fmt"
)

func main() {
	defer func() {
		defer func() {
			fmt.Println(recover())
		}()
	}()
	panic("abcd")
}

See https://play.golang.org/p/0BULKAck6b6.

The recover returns nil, and the program panics.

What did you expect to see?

From the spec:

Suppose a function G defers a function D that calls recover and a panic occurs in a function on the same goroutine in which G is executing. When the running of deferred functions reaches D, the return value of D's call to recover will be the value passed to the call of panic.

In this case, G is the function deferred in main, and D is the func() { fmt.Println(recover()) } which is deferred in G. When there is the panic in the same goroutine the G runs, the recover does not recover the panic.

I did some experiments and it seems the recover in D only recovers panics inside G, assuming D is deferred in G. So probably the spec can be more accurate.

Activity

  1. ianlancetaylor commented on Jan 24, 2018

    @ianlancetaylor
    Contributor

    The spec is accurate. In your example, there is no panic that occurs in the goroutine in which G is executing. A panic occurred before G started.

    This is working as intended. It is intended because any other approach would make it impossible for the deferred function (G) to reliably call a function that itself uses panic/recover.

    Closing. If you want to discuss this further, please use a forum (https://golang.org/wiki/Questions), not the issue tracker. Thanks.

  2. locked and limited conversation to collaborators on Jan 24, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions