Statement after a return, throw, break or continue
ID |
apex.correctness.code_reachable |
Severity |
high |
Remediation Complexity |
trivial |
Remediation Risk |
medium |
Remediation Effort |
low |
Resource |
Dead Code |
Language |
Apex |
Description
Reports a statement that directly follows a return, throw, break or continue in the same block, where control has already left and the statement can never run.
Rationale
Unreachable code is not merely useless: it is usually the part of the method that was supposed to run. A return added while debugging, or a throw moved up during a refactor, silently cuts off everything below it - the DML that saves the record, the callout, the assertion. The method still compiles and its tests may still pass, because the tests exercise the path that now ends early.
The following code illustrates the pattern detected by this rule:
public class Reachability {
public Integer compute(Integer seed) {
// FLAGGED: Statement after a return, throw, break or continue
return seed;
System.debug('never runs');
}
public void guard(Account a) {
// FLAGGED: Statement after a return, throw, break or continue
throw new IllegalArgumentException('bad record');
insert a;
}
public void loop(List<Account> accts) {
for (Account a : accts) {
if (a.Name == null) {
// FLAGGED: Statement after a return, throw, break or continue
continue;
System.debug('never runs');
}
System.debug(a.Name);
}
}
public Integer ok(Integer seed) {
if (seed == null) {
return 0;
}
System.debug('reached');
return seed;
}
}