2

我有两个类继承自java.lang.Exception. 他们都有一个具有相同签名的方法void a(){...}。它们都可以放在代码块中。如果我做:

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

然后它不会编译,因为方法a()不属于异常。这是Java语言缺陷吗?我应该如何正确设计我的代码以防止代码冗余?

4

2 回答 2

3

当您在单个 catch 语句中捕获多个异常类型时,所捕获异常的推断类型是这些类的最大公分母。在您的情况下,最大的公分母是Exception,它没有方法void a()。为了让 catch 块可以访问它,您可以将它提取到一个公共基类中,或者(可以说)更优雅地在两个类都实现的接口中定义它:

public interface SomeExceptionInterface {
    void a();
}

public class SomeException extends Exception implements SomeExceptionInterface {
    // Implementation...
}

public class SomeException2 extends Exception implements SomeExceptionInterface {
    // Implementation...
}
于 2017-06-01T17:08:59.287 回答
2

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.

于 2017-06-01T17:06:36.120 回答