I recommend ignoring the other reply you just got. They are clearly building a bad faith argument to try to make Go look terrible while claiming to sing its praises. That is not at all how that would look in Go. The point being made was that the exception-based code has lots of hidden gotchas, and being more explicit makes the control flow more obvious.
Something like this:
a, err := f()
if err != nil {
c, err := h()
if err != nil {
return fmt.Errorf("h failed: %w", err)
}
cleanupC(c)
return fmt.Errorf("f failed: %w", err)
}
defer cleanupA(a)
b, err := a.g()
if err != nil {
c, err := h()
if err != nil {
return fmt.Errorf("h failed: %w", err)
}
cleanupC(c)
return fmt.Errorf("a.g failed: %w", err)
}
defer cleanupB(b)
// the rest of the function continues after here
It’s not crazy.
With Java’s checked exceptions, you at least have the compiler helping you to know (most of) what needs to be handled, compared to languages that just expect you to find out what exceptions explode through guess and check… but some would argue that you should only handle the happy path and let the entire handler die when something goes wrong.
I generally prefer the control flow that languages like Rust, Go, and Swift use.
Errors are rarely exceptional. Why should we use exceptions to handle all errors? Most errors are extremely expected, the same as any other value.
I’m somewhat sympathetic to the Erlang/Elixir philosophy of “let it crash”, where you have virtually no error handling in most of your code (from what I understand), but it is a very different set of trade offs.
Something like this:
It’s not crazy.With Java’s checked exceptions, you at least have the compiler helping you to know (most of) what needs to be handled, compared to languages that just expect you to find out what exceptions explode through guess and check… but some would argue that you should only handle the happy path and let the entire handler die when something goes wrong.
I generally prefer the control flow that languages like Rust, Go, and Swift use.
Errors are rarely exceptional. Why should we use exceptions to handle all errors? Most errors are extremely expected, the same as any other value.
I’m somewhat sympathetic to the Erlang/Elixir philosophy of “let it crash”, where you have virtually no error handling in most of your code (from what I understand), but it is a very different set of trade offs.