0

我在 Eclipse 中使用以下代码:

public class Foo {
    public static final Bar bar = new Bar(20);
}

public class Bar {
    public int value;

    // This needs to be able to be called in places other than
    // just Foo, and there it will need to throw.
    public Bar(int value) throws Exception {
        if(value == 0) {
            throw Exception("Error. Value cannot be 0 when constructing Bar.");
        }
        return;
     }
}

这在 Foo(第 2 行)中给了我一条错误消息,上面写着“未处理的异常类型异常”,即使在实践中,此代码永远不会发生此异常。我可以在 Eclipse 中禁用此错误,以免打扰我,还是有其他方法可以处理此错误?

提前感谢您的答案!

4

2 回答 2

1

这是一个编译器错误,需要修复以编译 Java 代码,而不是 Eclipse 问题:检查的异常需要在 Java 中通过使用-或传递异常(方法/构造函数...)来显式处理。trycatchthrows

如果Bar无法更改类,一种可能性是使用私有静态方法来初始化常量 bar(应BAR根据 Java 命名约定命名):

public class Foo {

    public static final Bar BAR = initBar(20);

    private static Bar initBar(int value) {
        try {
            return new Bar(20);
        } catch (InvalidCharacterException e) {
            return null;
        }
    }

}
于 2018-10-20T09:00:13.360 回答
0

用 try/catch 包围构造函数以捕获异常。

像这样:

public class Foo {

try {
    public static final Bar = new Bar(20);
}catch(InvalidCharacterException e) {
    e.PrintStackTrace();
}

应该解决你的问题。如果没有,请随时回复,我会尽力帮助您。

于 2018-10-19T22:59:38.033 回答