跳到主內容

use_rethrow_when_possible

穩定
推薦
可用修復

使用 rethrow 來重新丟擲捕獲到的異常。

詳情

#

摘自 Effective Dart

使用 rethrow 來重新丟擲捕獲到的異常。

由於 Dart 提供了 rethrow 這個功能,因此應該使用它來提高程式碼的簡潔性和可讀性。

dart
try {
  somethingRisky();
} catch(e) {
  if (!canHandle(e)) throw e;
  handle(e);
}

dart
try {
  somethingRisky();
} catch(e) {
  if (!canHandle(e)) rethrow;
  handle(e);
}

啟用

#

要啟用 use_rethrow_when_possible 規則,請在您的 analysis_options.yaml 檔案中,將 use_rethrow_when_possible 新增到 linter > rules

analysis_options.yaml
yaml
linter:
  rules:
    - use_rethrow_when_possible

如果您使用 YAML 對映語法來配置 linter 規則,請將 use_rethrow_when_possible: true 新增到 linter > rules

analysis_options.yaml
yaml
linter:
  rules:
    use_rethrow_when_possible: true