Skip to content

Conversation

@divinerapier
Copy link

修复嵌套 defer 函数中的 recover 无法正确捕获 painc

测试代码如下:

package main

import "fmt"

func main() {
	fmt.Println("testRecover")
	testRecover()

	fmt.Println("testNestedRecover")
	testNestedRecover()

	fmt.Println("main end")
}

func foo() {
	panic("foo panic")
}

func testRecover() {
	defer func() {
		if err := recover(); err != nil {
			fmt.Println("recover: ", err)
		}
	}()

	foo()

}

func testNestedRecover() {
	defer func() {
		defer func() {
			if err := recover(); err != nil {
				fmt.Println("recover: ", err)
			}
		}()
	}()

	foo()
}

运行结果:

go run test_recover.go
testRecover
recover:  foo panic
testNestedRecover
panic: foo panic

goroutine 1 [running]:
main.foo(...)
        /Users/divinerapier/test_recover.go:16
main.testNestedRecover()
        /Users/divinerapier/test_recover.go:39 +0x4c
main.main()
        /Users/divinerapier/test_recover.go:10 +0x88
exit status 2

运行结果未按照期望输出 main end

@Harry-zklcdc Harry-zklcdc reopened this Nov 28, 2025
@github-actions github-actions bot locked and limited conversation to collaborators Nov 28, 2025
@Harry-zklcdc

This comment was marked as outdated.

@Harry-zklcdc Harry-zklcdc reopened this Nov 28, 2025
@XShengTech XShengTech unlocked this conversation Nov 28, 2025
@Harry-zklcdc Harry-zklcdc reopened this Nov 28, 2025
@Harry-zklcdc
Copy link
Member

recheck

@github-actions
Copy link


Thank you for your submission, we really appreciate it. Like many open-source projects, we ask that you sign our Contributor License Agreement before we can accept your contribution. You can sign the CLA by just posting a Pull Request Comment same as the below format.


I have read the CLA Document and I hereby sign the CLA


You can retrigger this bot by commenting recheck in this Pull Request. Posted by the CLA Assistant Lite bot.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants