Unreachable Code

ID

java.unreachable_code

Severity

low

Remediation Complexity

auto_fix

Remediation Risk

low

Remediation Effort

low

Resource

Dead Code

Language

Java

Tags

dead-code, reliability

Description

Reports the first statement that appears after a terminating statement in the same block. The terminators are return, throw, break, continue, and never-returning calls such as System.exit(…​). A statement that follows an always-taken constant branch (for example the code after an if (false) { …​ }) is reported as well. Such a statement can never be executed.

Rationale

Code that follows an unconditional jump or process exit is dead code. It misleads readers who may believe the code does something meaningful, and it typically indicates a logic error (the jump was meant to be conditional) or leftover code from a refactoring. The Java compiler rejects some forms of unreachable code outright, but many — such as statements after System.exit or inside an always-false branch — compile cleanly and slip through.

int first(int[] items) {
    return items[0];
    System.out.println("returned"); // FLAW — never reached after return
}

void shutdown() {
    System.exit(1);
    cleanup(); // FLAW — never reached after System.exit
}

void bounded(int[] items) {
    for (int v : items) {
        if (v < 0) {
            continue;
        }
        process(v); // OK — reachable on the non-negative path
    }
}

Remediation

Remove the unreachable statement. If it was meant to execute, move the terminating statement after it, or make the terminating statement conditional.