3 ms·
In my experience, the majority of the time, all you want to do with an error is to pass it on to the function above, while adding some amount of context to be a
by tsimionescu 4y ago
In my experience, the majority of the time, all you want to do with an error is to pass it on to the function above, while adding some amount of context to be able to later tell where it appeared in this function. Exceptions with stack traces (Java, C#, Python, Common Lisp - really anything except C++) give you both things for free: control flow stops, the function calling you gets the error, and information about where the error occurred is passed on.
At component boundaries you typically catch the error and perhaps convert it into a different type; and somewhere close to the user interface level you typically actually handle it in some meaningful way (retry operation, show error to user, cancel other work etc). Here by user interface I don't mean just GUI, but things like HTTP request handlers, terminal UI, RPC etc.
In most codebases that I've seen, error handling (as opposed to bubbling the error up with a bit of added context) is perhaps 1% of cases - whether in Java or Go or C. And in Java, this just means that 99% of cases will "handle" an error by simply calling a function, or perhaps the try-with-resources statement.
- klodolph 4y agoI find stack traces to contain more noise and less signal than the error messages I see in Go. So the idea that exceptions with stack traces give you “both things for free” doesn’t match my experience. I have professional experience in both software engineering and operations for apps written in both styles—from my experience, using exceptions makes it easier to write the code, and harder to diagnose errors in the running application.
- tsimionescu 4y agoSure, well crafted error traces will always beat automatically generated stack traces. However, in my experience debugging both local and customer issues based on logs, exceptions are, say, 80% of the way there, and they neither pollute your code nor leave you with 0 information if someone was lazy or in a hurry to ship something. Personally, I feel that what exceptions with stack traces get you is going to be the best trade-off between nice error messages in logs VS amount of effort in code spent to detail error paths. Of course, this doesn't have to be a 100% trade-off, and exceptions still allow you to add extra context whenever you feel it is necessary. Even if you decide to do it 100% of the time, they still act as an excellent safety net, making sure that you can't forget about an error, and need not be more verbose than if err!=nil checks or matches on the Result type (though I admit they do tend to be more verbose in most languages, requiring an extra block for try to be introduced).