3 ms·
Can 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 e
by baby 9y ago
Can 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.