Reputation: 1171
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?
Upvotes: 2
Views: 641
Reputation: 312106
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...
}
Upvotes: 3
Reputation: 20658
If you need to access a method called a()
, you need a type that provides that method. A simple solution could be:
public class AbstractSubException extends Exception {
public abstract void a();
}
public class SubException1 extends AbstractSubException {
@Override public void a() { ... }
}
public class SubException2 extends AbstractSubException {
@Override public void a() { ... }
}
Then you can catch the way you did or (somewhat simpler):
catch (AbstractSubException e) {
e.a();
}
Maybe the code for the method a
is the same in all sub classes. Then you can make it concrete and put the code into the parent class.
Upvotes: 2