Boyarsky, Jeanne; Selikoff, Scott. OCP Oracle Certified Professional Java SE 11 Developer Complete Study Guide (p. 420). Wiley. Kindle Edition.
In a subchapter: Applying a Multi-catch Block
Under this code:
Authors wrote this:
How can you reduce the duplicate code? One way is to have the related exception classes all inherit the same interface or extend the same class. For example, you can have a single catch block that just catches Exception. This will catch everything and anything.
I don't understand how would inheriting the same interface help here? I cannot use interface in the catch clause. If they extend the same exception, then they will be handled by the same block, I can understand that.
There is too much left untold and left to the user to ponder how one would solve it with interfaces...
Rade Koncar wrote:Since exceptions are defined as classes they can implement an interface, but I wonder what the authors meant by this...
Then I'd agree with you. I never thought of having a class extend Exception and also implement an interface, but there's no rule against it so why not? But apparently that isn't useful, at least not for catching those exceptions. Unless both of us are missing something, which is still possible.
No, you can make an exception implement an interface (e.g. Serializable, which most exceptions already implement). But you cannot catch it as Serializable; there is no way to know that a Serializable is an exception class.