3 ms·
That's simply not true. There is no recovering from a failed assert. Go's recover() allows recovering from panics. Further, it is considered good practice to r
by gmfawcett 9y ago
That's simply not true. There is no recovering from a failed assert. Go's recover() allows recovering from panics.
Further, it is considered good practice to recover from panics within library API boundaries, and return errors across the API instead. "The convention in the Go libraries is that even when a package uses panic internally, its external API still presents explicit error return values."[1]
[1] https://blog.golang.org/defer-panic-and-recover https://blog.golang.org/defer-panic-and-recover
- NateDad 9y agoYes, if you use panics for control flow in your package, you need to recover from them and hide that fact from your API. That is not the same as saying that you should recover from any panics that happen inside your library. Unexpected panics basically always indicate a programmer error.
- baby 9y agoCan you give me example in the standard library where they recover from a panic? So far I've only seen recovery through error handling. I think the crypto/tls example is pretty telling on the way they're using panic for sensitive code. No recovery there.
- NateDad 9y agoIt's common in parsers. JSON parsing can panic (IIRC), as does the go template parsing code. Would they still write it that way today? I don't know.
- joeshaw 9y agoIn net/http, if a handler panics you don't want it to bring down your entire application. For more info, see https://golang.org/pkg/net/http/#Handler https://golang.org/pkg/net/http/#Handler The encoding/json package is interesting because it uses both panic() and recover() internally in a way more reminiscent to how exceptions are used in other languages (that is, for control flow). For example, https://github.com/golang/go/blob/2596a0c075aeddec571cd658f748ac7a712a2b69/src/encoding/json/decode.go#L298-L301 https://github.com/golang/go/blob/2596a0c075aeddec571cd658f7... panics, and https://github.com/golang/go/blob/2596a0c075aeddec571cd658f748ac7a712a2b69/src/encoding/json/decode.go#L172-L179 https://github.com/golang/go/blob/2596a0c075aeddec571cd658f7... recovers it. Both uses are quite uncommon, though.
- baby 9y agointeresting! Yeah this is definitely changing my idea of how panic should be used.