在Java中,尝试捕获未在try块中抛出的异常是编译时错误,但在方法中声明抛出的checked-exception不是编译时错误,即使该方法实际上不能抛出该异常。
但是,在eclipse中,可以通过编译器配置(http://help.eclipse.org/mars/index.jsp?topic=%2Forg.eclipse.jdt.doc.user%2Freference%2Fpreferences%2Fjava%2Fcompiler%2Fref-preferences-errors-warnings.htm)更改此设置。
是否可以通过编译器标志在标准java编译过程中产生相同的行为?具体来说,我想将此检查集成到maven构建中。声明的无法抛出的异常会产生不必要的catch块,错误处理程序,甚至单元测试都会分散现有代码的进一步调试和扩展,并产生浪费,不必要的工作来捕获和测试这些异常。
我们能否强制执行清洁工"编码标准通过java编译器?
答案 0 :(得分:1)
Can we enforce a "cleaner" coding standard via the java compiler?
For versions of Java up to Java 9, the answer is No. Or at least, that is what the javac
manual is telling me (7, 8 & 9).
The way to be sure about this would be to enable all warnings (-Xlint:all
) and see if you get a warning message for a redundant throws
clause.
Actually:
In Java, it is a compile-time error to attempt to catch an exception that is not thrown in the try block ...
this is only true for checked exceptions. The compiler cannot tell if an unchecked exception can be thrown ... in many cases.