I'm curious because I've never felt it being onerous nor felt like there was much friction. Perhaps because I've primarily built web applications and web APIs, it's very common to simply let the exception bubble up to global middleware and handle it at a single point (log, wrap/transform). Then most of the code doesn't really care about exceptions.
The only case where I might add explicit exception handling probably falls into a handful of use cases when there is a desire to a) retry, b) log some local data at the site of failure, c) perform earlier transform before rethrowing up, d) some cleanup, e) discard/ignore it because the exception doesn't matter.
If you need to handle errors, you quickly get into extremely complicated control flow that you now have to test:
// all functions can throw, return nil or not.
// All require cleanup.
try {
a = f();
b = a.g();
} catch(e) {
c = h();
} finally {
if a cleanup_a() // can throw
if b cleanup_b() // null check doesn’t suffice…
if c cleanup_c()
}
Try mapping all the paths through that mess. It’s 6 lines of code. 4 paths can get into the catch block. 8 can get to finally. Finally multiplies that out by some annoying factor.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.
handleError := func(origErr error, context string) error {
c, err := h()
if err != nil {
return fmt.Errorf("%s: h failed: %w", context, err)
}
cleanupC(c)
return fmt.Errorf("%s: %w", context, origErr)
}
a, err := f()
if err != nil {
return handleError(err, "f failed")
}
defer cleanupA(a)
b, err := a.g()
if err != nil {
return handleError(err, "a.g failed")
}
defer cleanupB(b)
// the rest of the function continues after here
It is just an explicit rendition of a complex topic.
Do you have a more economical example that handles all of the corner cases of cleanup routines throwing errors?