Hacker News new | ask | show | jobs
by Deadron 2104 days ago
One of the bigger problems is that exceptions are slow. Thus the recommendation is not to use them in cases where the caller could branch on. A perfect example is a missing element in a remote system. An old api would throw some sort of a Element Not Found Exception. With the addition of Optional though you have a object that is easier to use, conveys your intention better, and doesn't have any of the performance drawbacks. I think what it comes down to is that when dealing with situations that might be handled by the caller you should use some sort of result object instead of a exception. This leaves exceptions only for the cases where the result cant be handled. In which case you dont need checked exceptions.
3 comments

> A perfect example is a missing element in a remote system. An old api would throw some sort of a Element Not Found Exception.

Wait, if the example involves a remote system how can the Exception be the bottleneck? Even generating the completely optional stacktrace shouldn't take that much time.

Exceptions are slow to throw, but they're meant to be exceptional so that's OK. Good implementations impose no overhead the rest of the time. This is not the case for return type based systems, where you can easily end up with an allocation that must be GCd later.
Not as slow as many people think, especially with things like OmitStackTraceInFastThrow
OmitStackTraceInFastThrow has caused so many headaches in debugging production issues, and each time now the answer has been to just disable it. The real answer is to stop trying to abuse exceptions as a form of general control flow.
For some reason the most talked about "alternative" to exceptions seems to be "use optional". I would assume that this has the same debug issues as omitting the stack trace.
> I would assume that this has the same debug issues as omitting the stack trace.

I don't expect so. If I "forget to handle" an optional, I get an error at compile time pointing at the lines in question. If I forget to handle an exception with an omitted stack trace, IIUC, I am told at runtime that there's an error somewhere in my program. It's much easier to debug the former.