Let’s hope Go never gets try/catch exceptions
func try(fn func()) { fn() }
func catch(fn func(any)) {
if v := recover(); v != nil {
fn(v)
}
}
func throw(v any) { panic(v) }
func fail() {
throw("Bad things have happened")
}
func main() {
try(func() {
defer catch(func(v any) {
fmt.Println(v)
})
fail()
})
}
Sorry.The API reference doesn't state that panics are a part of the expected error interface, and the source code references seem to be using panics as a way to validate invariants. Is that what you're referring to?
I'm not entirely sure if the panics are _just_ for sanity, or if input truly can cause a panic. If it's the latter, then I agree - yikes.
[1] - https://pkg.go.dev/encoding/json
[2] - https://cs.opensource.google/search?q=panic&sq=&ss=go%2Fgo:s...
The syscall/js package [0] throws panics if something goes wrong, rather than returning errors.
Go already has try/catch exceptions. We just don't use them most of the time because they're a really bad way of handling errors.