3 ms·
No, panic/recover is a major hack. Rob Pike has written ideas here on how to clean up error handling if-blocks: http://blog.golang.org/errors-are-values http:
by pdq 11y ago
No, panic/recover is a major hack.
Rob Pike has written ideas here on how to clean up error handling if-blocks: http://blog.golang.org/errors-are-values http://blog.golang.org/errors-are-values
- burntsushi 11y agoNo, it's not a "major hack." That blog post is excellent, but it just doesn't always apply. The panic/recover idiom is extremely useful in parsers. For example, Go's JSON decoder: http://golang.org/src/encoding/json/decode.go http://golang.org/src/encoding/json/decode.go
- pdq 11y agoThe difference is that in parsers, errors are almost certainly fatal. As opposed to a runtime SQL error, where it could be a user error, value error, or other database error, which can be recovered from. Panic/recover are usually meant to catch "coding" and "assertion"-type errors (null pointers, array overflows, etc), not runtime errors. The latter is what the "error" values are used for.
- thirsteh 11y agoPanic/recover is no problem as long as it does not traverse API boundaries, i.e. affects the user of your package, unless it really is a "fatal user error" in a function that wouldn't otherwise return an error.
- burntsushi 11y agoI'm pretty sure you've misunderstood. Did you read the code I linked you to? Look at how it handles errors internally. Go's standard JSON decoder isn't going to crash your program if it fails to parse JSON---that would be disastrous. It exposes regular errors to the user. But internally, it uses panic/recover because it elides a lot of manual error checking.
- superuser2 11y agoInteresting. That's basically the Maybe monad.