For AI agents: A markdown version of this page is available at https://docs.datadoghq.com/security/code_security/static_analysis/static_analysis_rules/dart-code-quality/control-flow-in-finally.md. A documentation index is available at /llms.txt.

Avoid control flow statements in finally blocks

This product is not supported for your selected Datadog site. ().

Metadata

ID: dart-code-quality/control-flow-in-finally

Language: Dart

Severity: Warning

Category: Code Style

Description

Using return, break, continue, or throw inside a finally block overrides any exception or return value propagating out of the try/catch, silently swallowing errors and producing surprising control flow.

Move these statements out of the finally block. Control flow that stays within a nested construct declared there, such as a break inside a loop or a return inside a closure, is fine.

Non-Compliant Code Examples

int returnInFinally() {
  try {
    return doWork();
  } finally {
    return 0;
  }
}

void breakInFinally() {
  for (var i = 0; i < 3; i++) {
    try {
      risky();
    } finally {
      break;
    }
  }
}

void continueInFinally() {
  for (var i = 0; i < 3; i++) {
    try {
      risky();
    } finally {
      continue;
    }
  }
}

void throwInFinally() {
  try {
    risky();
  } finally {
    throw StateError('overrides');
  }
}

int doWork() => 1;
void risky() {}

Compliant Code Examples

void ordinaryCleanup() {
  var closed = false;
  try {
    risky();
  } finally {
    closed = true;
    cleanup();
    print(closed);
  }
}

void breakInsideNestedLoop() {
  try {
    risky();
  } finally {
    for (var i = 0; i < 10; i++) {
      if (i == 5) break;
      if (i == 3) continue;
    }
    var j = 0;
    while (j < 3) {
      j++;
      if (j == 2) break;
    }
  }
}

void returnInsideClosure() {
  try {
    risky();
  } finally {
    final compute = () {
      return 42;
    };
    compute();
  }
}

void throwInsideClosure() {
  try {
    risky();
  } finally {
    final validate = (int x) {
      if (x < 0) throw ArgumentError('negative');
    };
    validate(1);
  }
}

void risky() {}
void cleanup() {}
https://static.datadoghq.com/static/images/logos/github_avatar.svg https://static.datadoghq.com/static/images/logos/vscode_avatar.svg jetbrains

Seamless integrations. Try Datadog Code Security