3 ms·
> I trust that the "typed exceptions are an antipattern" people know what they're talking about, but I really don't understand the reasoning behind that positio
by Someone 2y ago
> I trust that the "typed exceptions are an antipattern" people know what they're talking about, but I really don't understand the reasoning behind that position.
The reasoning is that they force a contract upon implementations that they may not be able to implement in spirit.
Let’s say a library defines a container interface that says a method can throw a NoSuchElementException.
Now, I implement that interface to implement a disk backed container. What do I do when that code encounters an IOException? Swallow it (very bad), throw an NoSuchElementException, possibly wrapping the IOException inside it, if possible (highly confusing, as now the class changed the meaning of NoSuchElementException), or throw an unchecked exception that wraps it instead?
Most Java code would pick that last option, and you end up with a nice interface that says that a call can throw NoSuchElementException, but callers must be prepared to get a RuntimeException that wraps any other kind of exception.
That makes the implementation adhere to the interface, but only in name.
(Note that the writers of the interface, the implementation of the disk-backed container, and the user of that container often all will be different teams at different organizations)
So, why declare that typed exception, in the first place?
- 9dev 2y agoBut isn’t the actual advantage here that it gives me the ability to handle that error case specifically? I mean stuff like IO errors can happen everywhere at any time anyway, but if I need to do something specifically if there is no such element, isn’t that a plus? Otherwise, I’d have no chance to handle that error if I can do so.
- MBCook 2y agoHandling there is probably the right thing to do. I think the argument is that there is probably a better way of expressing that in code than exceptions. Perhaps returning an Either<Data, ErrorCode> kind of value. There’s also an argument that that’s not truly an exception because it should be expected that an I/O error is a reasonable possibility. Things like OutOfMemory or VirtualMachineError are more what they may be thinking exceptions should be saved for. Truly unexpected things.