跳到主要内容

control_flow_in_finally

稳定
推荐

避免在 finally 代码块中使用控制流。

详情

#

避免控制流离开 finally 代码块。

finally 代码块中使用控制流将不可避免地导致意外行为,且难以调试。

错误示例

dart
class BadReturn {
  double nonCompliantMethod() {
    try {
      return 1 / 0;
    } catch (e) {
      print(e);
    } finally {
      return 1.0; // LINT
    }
  }
}

错误示例

dart
class BadContinue {
  double nonCompliantMethod() {
    for (var o in [1, 2]) {
      try {
        print(o / 0);
      } catch (e) {
        print(e);
      } finally {
        continue; // LINT
      }
    }
    return 1.0;
  }
}

错误示例

dart
class BadBreak {
  double nonCompliantMethod() {
    for (var o in [1, 2]) {
      try {
        print(o / 0);
      } catch (e) {
        print(e);
      } finally {
        break; // LINT
      }
    }
    return 1.0;
  }
}

正确示例

dart
class Ok {
  double compliantMethod() {
    var i = 5;
    try {
      i = 1 / 0;
    } catch (e) {
      print(e); // OK
    }
    return i;
  }
}

启用

#

要启用 control_flow_in_finally 规则,请在您的 analysis_options.yaml 文件中的 linter > rules 下添加 control_flow_in_finally

analysis_options.yaml
yaml
linter:
  rules:
    - control_flow_in_finally

如果您改为使用 YAML 映射语法来配置 linter 规则,请在 linter > rules 下添加 control_flow_in_finally: true

analysis_options.yaml
yaml
linter:
  rules:
    control_flow_in_finally: true