Skip to content

else_after_leaving_branch

Reports the else of an if whose first branch always leaves. Move the code of the else to after the if.

Tier
advisory
Scope
Dart
Lowest preset
strict
Fix
lifts the code of the else out to after the if

The else of an if whose first branch always leaves, where the else itself may complete. The violation is on the else.

A branch always leaves when it ends in return, throw, rethrow, break or continue without a label, or an expression of type Never such as exit(1). That holds on the branch’s own level, or in an if whose two branches both leave.

It does not report:

  • an else that always leaves as well: if (ready) { return start(); } else { return wait(); } is one choice between two ways out;
  • a first branch that may complete, such as a return inside a try whose catch goes on;
  • a jump with a label;
  • an else if, or an if that is itself an else;
  • an if that is not among the statements of a block or a case;
  • an empty else, which empty_block reports.

The fix is not offered where the else declares a name on its own level, holds a string that spans lines, or where a comment stands between the first branch and its code.

The code of the else runs only where the first branch did not, so it can stand after the if, one level less deep.

Violating
if (value < 0) {
return;
} else {
into.add(value);
}
Corrected
if (value < 0) {
return;
}
into.add(value);

Set under the assay: key of the project’s root analysis_options.yaml.

Rule parameter Default Effect
enabled true false switches the rule off for the whole project.
exclude [] Path globs where the rule is silent.

Write why on the line directly above the suppression:

// Why it stays as written here.
// ignore: else_after_leaving_branch

// ignore_for_file: assay/else_after_leaving_branch silences it in a whole file, and // ignore: assay/else_after_leaving_branch with the prefix works too. See Suppressions.