go: runtime: recover added in range-over-func loop body doesn't stop panic propagation / segfaults printing error

Go version

go version go1.23.2 darwin/amd64

Output of go env in your module/workspace:

GO111MODULE='on'
GOARCH='amd64'
GOBIN=''
GOCACHE='/Users/acorn/Library/Caches/go-build'
GOENV='/Users/acorn/Library/Application Support/go/env'
GOEXE=''
GOEXPERIMENT=''
GOFLAGS=''
GOHOSTARCH='amd64'
GOHOSTOS='darwin'
GOINSECURE=''
GOMODCACHE='/Users/acorn/go/pkg/mod'
GONOPROXY=''
GONOSUMDB=''
GOOS='darwin'
GOPATH='/Users/acorn/go'
GOPRIVATE=''
GOPROXY='direct'
GOROOT='/Users/acorn/go/pkg/mod/golang.org/toolchain@v0.0.1-go1.23.2.darwin-amd64'
GOSUMDB='sum.golang.org'
GOTMPDIR=''
GOTOOLCHAIN='auto'
GOTOOLDIR='/Users/acorn/go/pkg/mod/golang.org/toolchain@v0.0.1-go1.23.2.darwin-amd64/pkg/tool/darwin_amd64'
GOVCS=''
GOVERSION='go1.23.2'
GODEBUG=''
GOTELEMETRY='local'
GOTELEMETRYDIR='/Users/acorn/Library/Application Support/go/telemetry'
GCCGO='gccgo'
GOAMD64='v1'
AR='ar'
CC='clang'
CXX='clang++'
CGO_ENABLED='1'
GOMOD='/Users/acorn/go-demo/go.mod'
GOWORK=''
CGO_CFLAGS='-O2 -g'
CGO_CPPFLAGS=''
CGO_CXXFLAGS='-O2 -g'
CGO_FFLAGS='-O2 -g'
CGO_LDFLAGS='-O2 -g'
PKG_CONFIG='pkg-config'
GOGCCFLAGS='-fPIC -arch x86_64 -m64 -pthread -fno-caret-diagnostics -Qunused-arguments -fmessage-length=0 -ffile-prefix-map=/var/folders/6c/6skkl1zn2p9fcx2r70v0kyc00000gn/T/go-build362480746=/tmp/go-build -gno-record-gcc-switches -fno-common'

What did you do?

When traversing an iterative function, there are some peculiar behaviors that arise concerning the defer within the loop, the panic in the outer function surrounding the loop, and the panic within the iterative function itself.

Here is a simple example that can trigger a segmentation fault. Below, I provide several links containing reproductions of a few peculiar behaviors.

func main() {
	for range yieldInts {
		defer func() {
			log.Println("recover:called")
			recover()
		}()
	}
}

func yieldInts(yield func(int) bool) {
	if !yield(0) {
		return
	}
	log.Println("will panic")
	panic("stop")
}

output:

2025/02/12 14:34:15 will panic
2025/02/12 14:34:15 recover:called
fatal error: panic while printing panic value: type runtime.errorString
[signal SIGSEGV: segmentation violation code=0x1 addr=0x29 pc=0x9e0d613]
...

What did you see happen?

2025/02/12 14:34:15 will panic
2025/02/12 14:34:15 recover:called
fatal error: panic while printing panic value: type runtime.errorString
[signal SIGSEGV: segmentation violation code=0x1 addr=0x29 pc=0x9e0d613]
...

Bizarre Behavior One Bizarre Behavior two Bizarre Behavior three

This issue likely arises from the compiler’s handling of the stack when transforming the for loop body into a range function.

What did you expect to see?

I hope to observe behavior that aligns exactly with what is described in this official documentation. It should not include those unpredictable and peculiar behaviors that it does not describe.

About this issue

  • Original URL
  • State: closed
  • Created 2 years ago
  • Reactions: 1
  • Comments: 29 (8 by maintainers)

Commits related to this issue

Most upvoted comments

I found another bizarre behavior example: https://go.dev/play/p/gqqk-mrkqpB (changed a bit on Bizarre Behavior two).

package main

import “log”

func main() { for n := range yieldInts { defer func() { log.Println(n, “recover:called”) log.Println(recover()) }() } panic(3) }

var i = 0

func yieldInts(yield func(int) bool) { for { if i == 2 { break } if !yield(i) { return } i++ } } It looks the two deferred recover call both catch the panic, but don’t remove the panic from the panic stack.

[edit] sorry, this should be the same as Bizarre Behavior two in principle.

Are you the author of the “Go101” series? It’s truly a pleasure to meet you here. I’ve had the chance to read your work, and I must say, it’s incredibly detailed and serves as an excellent reference book. It has been of great help to me, and for that, I am deeply grateful. Thank you very much.

@gopherbot, this needs a backport to 1.24 and 1.23. The fix is simple, and this was supposed to work.

Maybe the best balancing tradeoff approach is to totally disable all recover calls in range functions. (a.k.a., adopt the Theory 2 mentioned above). This will avoid many confusions and easy the implementation.

If the Theory 1 is adopted, there will be still confusions in the following alike code. The panic in the code will be catched (if Theory 1 is adiopted). Some people might think this is weird.

package main

import "fmt"

func main() {
	defer foo()
	panic(123)
}

func foo() {
	for range iter {}
}

func iter(yield func(int) bool) {
	fmt.Println(recover())
	yield(0)
}

[edit] Sorry, it looks a new issue is needed to continue the discussion. It seems this is a different problem from both the current issue and https://github.com/golang/go/issues/71685.

Panicking in the loop body and after the loop body should have not semantic difference. That is it. Otherwise, it is strange to users.

What happens if the iterator function recovers a panic in the loop body?Go Wiki: Rangefunc Experiment The compiler and runtime will detect this case and trigger a [run-time panic]

Even if an exception is caught, a different exception is thrown again, which might be intended to align with the semantics of the call chain? However, logically, the iterator’s recovery could entirely disregard the panic within the loop body. Reprocessing it in this way seems to hold little significance?

However, since only the function to which the loop body belongs and its parent functions have the opportunity to recover from a panic triggered by the loop body, this actually contradicts the semantics of the call chain. The official call chain is as follows: the parent function of the loop body -> the iterator function -> the function constructed by the loop body. As a result, the iterator function can only catch a panic but cannot recover it, which seems quite unusual. It appears that there has never been such a case before.

Indeed, in the official implementation, there are cases where a parent function cannot catch exceptions from its child functions, while a grandparent function can. However, those parent functions are compiler-generated, such as generating corresponding pointer-type methods for non-pointer type methods. In those scenarios, users cannot access the parent function, allowing for a seamless handling. This situation is different and requires more contemplation? But now that it has been released, it’s too late. We’ll just have to wait for the official implementation to conform to the current specification constraints.