Go handles errors and exceptions better than Java ⚡
Java throws exceptions, while Go is more subtle and treats errors as first-class citizens requiring you to return them from one function to another across the stack.
In case of an exception, Java stops everything and waits until some function in the program flow catches it in a try-catch block. This is unnecessarily expensive, especially when the root cause is trivial. In such cases, it feels like a meeting that could just have been an email.
Here are a few pointers that I believe make Go’s style of error handling better than exceptions
- explicit error handling forces you to be pessimistic while you code
- this makes your code more robust and cleaner by design
- error objects are ~100x efficient than exceptions
- no complex exception hierarchies or checked exceptions to deal with
- in a highly concurrent environment, you can pass errors in special error channels and handle them in a clean, granular, and efficient way
I agree that in some scenarios, Go’s approach feels clunky, but it is still better than throwing and catching exceptions. This is why a lot of modern programming languages have adopted the no-hidden-control-flow approach.
By the way, the Go program does “panic” in case a big mess happens, and you can choose to recover from it just like try-catch. But given it is for critical cases, it feels like scheduling a meeting for something that requires a meeting.
Also, before you start smashing your keyboard and leaving an angry reply, understand this - when I say Java, read it as any language that relies on throwing heavy exceptions like Python and JavaScript.
ps: If you love Java, and you took offense in this post, read it again. It is not about Java but about lightweight error objects vs heavy exceptions.
⚡ I keep writing and sharing my practical experience and learnings every day, so if you resonate then follow along. I keep it no fluff.
youtube.com/c/ArpitBhayani