avoid_catches_without_on_clauses
避免使用未指定 on 子句的 catch。
詳細資訊
#避免使用未指定 on 子句的 catch。
使用未指定 on 子句的 catch 子句會使您的程式碼容易遇到未預期的錯誤,這些錯誤不會被拋出 (因此不會被注意到)。
不良示範
dart
try {
somethingRisky()
} catch(e) {
doSomething(e);
}
良好示範
dart
try {
somethingRisky()
} on Exception catch(e) {
doSomething(e);
}
允許少數例外情況
- 如果 catch 的主體重新拋出例外。
- 如果捕獲的例外「直接用於」
Future.error
、Completer.completeError
或FlutterError.reportError
的引數,或任何傳回類型為Never
的函式。 - 如果捕獲的例外「直接用於」新的 throw 運算式。
在這些情況下,「直接使用」表示例外在相關程式碼 (例如在引數中) 內被引用。如果例外變數在相關程式碼之前被引用,例如為了實例化包裝器例外,則該變數不被視為「直接使用」。
啟用
#若要啟用 avoid_catches_without_on_clauses
規則,請在您的 analysis_options.yaml
檔案中的 linter > rules 下新增 avoid_catches_without_on_clauses
analysis_options.yaml
yaml
linter:
rules:
- avoid_catches_without_on_clauses
如果您改為使用 YAML 對應語法來設定 linter 規則,請在 linter > rules 下新增 avoid_catches_without_on_clauses: true
analysis_options.yaml
yaml
linter:
rules:
avoid_catches_without_on_clauses: true
除非另有說明,否則本網站上的文件反映的是 Dart 3.7.1 版本。頁面最後更新於 2025-03-07。 檢視原始碼 或回報問題。