3 ms·
You can't have an interface implementation throw exceptions not declared in the interface, hence all implementations of a given interface have to declare the sa
by jrimbault 6y ago
You can't have an interface implementation throw exceptions not declared in the interface, hence all implementations of a given interface have to declare the same failure modes. And then everything is nicely coupled.
- kllrnohj 6y agoA great example of this is ByteArrayOutputStream's close(). It's documented to do literally nothing, and yet you still have to "handle" an IOException that will never, ever happen. https://docs.oracle.com/javase/7/docs/api/java/io/ByteArrayOutputStream.html#close() https://docs.oracle.com/javase/7/docs/api/java/io/ByteArrayO...
- hyperpape 6y agoThe language doesn't force them to do that--they could override the interface and not declare the Exception. Then if you were working with an object declared to be ByteArrayOutputStream, you wouldn't need to handle the Exception. If working with the interface, you would, because that's the point of an interface.
- twic 6y agoYes, this is a poor example. The declaration of that exception is either a mistake, or a way of reserving some wiggle room for future changes.
- hyperpape 6y agoThis is backwards of how I think about it, so I'm curious what you're thinking. If an implementation of an interface can throw an exception that its interface doesn't declare, that breaks the abstraction. How can you safely use the interface? You either have to catch Exception (which is effectively the same as wrapping every exception in some InterfaceException class), or give up on handling any Exceptions thrown by the interface.
- jrimbault 6y agoI don't think this is backward of your understanding ? That's just how I phrased it 18 hours ago. The thing I find bad about it is not that exceptions have to be declared in the interface, that's good, it's that every implementations will have to declare them also, even in the case that a particular implementation has no failure mode.
- hyperpape 6y agoThis sounds like a misconception. Implementations don't have to declare the exceptions: https://news.ycombinator.com/item?id=23410443 https://news.ycombinator.com/item?id=23410443.
- twic 6y agoThe interface can define a type parameter bounded to Throwable, and declare methods that throw that. But in general, of course an implementation can't just randomly add checked exceptions, because that would violate the Liskov substitution principle.