Dead code compile-time errors are defined by the compiler and not the IDE. While it is true the code will never get executed, it doesn't violate any of the rules for unreachable statements from the Oracle Docs.
From Unreachable Statements
This section is devoted to a precise explanation of the word "reachable." The idea is that there must be some possible execution path from the beginning of the constructor, method, instance initializer, or static initializer that contains the statement to the statement itself. The analysis takes into account the structure of statements. Except for the special treatment of while, do, and for statements whose condition expression has the constant value true, the values of expressions are not taken into account in the flow analysis.
The rules specifically for this case are related to whether or not the blocks you've created are reachable. (iff = if and only if)
An empty block that is not a switch block can complete normally iff it is reachable.
A non-empty block that is not a switch block can complete normally iff the last statement in it can complete normally.
The first statement in a non-empty block that is not a switch block is reachable iff the block is reachable.
Every other statement S in a non-empty block that is not a switch block is reachable iff the statement preceding S can complete normally.
The letsThrow
method meets the criteria for a working block of code and technically completes normally. It throws an exception, but it completes. Whether or not it throws a guaranteed exception is not taken into account in determining whether that block of code in its actual use, just whether or not it can be reached. In most cases, dead code will only be found when it involves try/catch/returns, which are the bulk of the rules.
Consider the following, even more concise version:
@Test
public void testDeadCode() {
System.exit(0);
System.out.println("will never be reached");
}
There's no real counter for this aside from diligent use of coverage tools, but the bright side in your example is you'll see guaranteed exceptions every time you run the code.
letsThrow()
method with lots of inner method calls. Do you ask the compiler to check the dead code in this situation for you too? Compiler is not almighty. – Torbertcatch(Whatever w) { tuneAndRethrow(w); throw Bla(w); }
so there is only one line of dead code. That would mean that I need close to 100% coverage for all our classes to find those places. Doesn't sound like a real plan to me. – Indefatigable