简体   繁体   中英

Configure Java Compiler for Error if method cannot throw declared checked Exception

In Java, it is a compile-time error to attempt to catch an exception that is not thrown in the try block, but it is not a compile-time error to declare a thrown checked-exception in a method, even when that method does not and in fact cannot throw that exception.

However, in eclipse, it is possible to change this via the compiler configuration ( http://help.eclipse.org/mars/index.jsp?topic=%2Forg.eclipse.jdt.doc.user%2Freference%2Fpreferences%2Fjava%2Fcompiler%2Fref-preferences-errors-warnings.htm ).

Is it possible to produce this same behavior during the standard java compilation process via compiler flags? Specifically, I want to integrate this checking into a maven build. Declared exceptions that cannot be thrown produce unnecessary catch blocks, error handlers, and even unit tests that all distract from the further debugging and extension of existing code and produce wasted, unnecessary effort to catch and test for these exceptions.

Can we enforce a "cleaner" coding standard via the java compiler?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM