---
title: Avoid control flow statements in finally blocks
description: Datadog, the leading service for cloud-scale monitoring.
breadcrumbs: >-
  Docs > Datadog Security > Code Security > Static Code Analysis (SAST) > SAST
  Rules > Avoid control flow statements in finally blocks
---

> For the complete documentation index, see [llms.txt](https://docs.datadoghq.com/llms.txt).

# Avoid control flow statements in finally blocks

{% callout %}
# Important note for users on the following Datadog sites: app.ddog-gov.com, us2.ddog-gov.com

{% alert level="danger" %}
This product is not supported for your selected [Datadog site](https://docs.datadoghq.com/getting_started/site.md). ({% placeholder "user-datadog-site-name" /%}).
{% /alert %}

{% /callout %}

## Metadata{% #metadata %}

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

**Language:** Dart

**Severity:** Warning

**Category:** Code Style

## Description{% #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{% #non-compliant-code-examples %}

```dart
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{% #compliant-code-examples %}

```dart
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() {}
```
  Seamless integrations. Try Datadog Code SecurityDatadog Code Security 
{% icon name="icon-external-link" /%}
 