javaexceptioncatch-blockmulti-catch

Undefined method in multiple-exception-catch


I have two classes inheriting from java.lang.Exception. They both have a method with the same signature void a(){...}. They both can be thrown in a code block. If I do:

catch (SubException1 | SubException2 e)
    {
        e.a();
    }

Then it won't compile because method a() does not belong to Exception. Is it a Java language flaw? How should I design my code properly to prevent code redundancy?


Solution

  • When you catch multiple exception types in a single catch statement the inferred type of the caught exception is the greatest common denominator of those classes. In your case, the greatest common denominator is Exception, which doesn't have the method void a(). In order to make it accessible to the catch block you could either extract it to a common base class, or (arguably) more elegantly, define it in an interface that both classes implement:

    public interface SomeExceptionInterface {
        void a();
    }
    
    public class SomeException extends Exception implements SomeExceptionInterface {
        // Implementation...
    }
    
    public class SomeException2 extends Exception implements SomeExceptionInterface {
        // Implementation...
    }