Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

spec: recover() in nested defer #23531

Closed
guangda-hu opened this issue Jan 24, 2018 · 1 comment
Closed

spec: recover() in nested defer #23531

guangda-hu opened this issue Jan 24, 2018 · 1 comment

Comments

@guangda-hu
Copy link

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.

@ianlancetaylor
Copy link
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.

@golang golang locked and limited conversation to collaborators Jan 24, 2019
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

No branches or pull requests

3 participants