我正在 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 中禁用此错误,这样它就不会打扰我,还是有其他方法可以处理此错误?
提前感谢您的回答!
最佳答案
这是一个编译器错误,需要修复才能编译 Java 代码,而不是 Eclipse 问题:检查异常需要在 Java 中通过包围它来显式处理使用 try
-catch
或传递异常(方法/构造函数 throws
.. .).
如果类 Bar
无法更改,一种可能是使用私有(private)静态方法来初始化常量 bar
(应该根据 Java 命名约定命名为 BAR
):
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;
}
}
}
关于java - 禁用 Eclipse Java Neon 中的错误提示/警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52900734/