Dart開發之——異常處理
阿新 • • 發佈:2021-02-08
一 概述
- Dart中的異常
- Dart中的異常處理
二 Dart中的異常
2.1 說明
- Dart使用throw關鍵字丟擲異常
- throw(“異常”)或throw “異常”
2.2 程式碼示例
main() {
var a = -1;
if (a < 0) {
throw "異常";
}
}
列印:
Unhandled exception: 異常 #0 main (file:///D:/Code/Dart/DartWhile/src/exception/MainException.dart:4:5) #1 _delayEntrypointInvocation.<anonymous closure> (dart:isolate-patch/isolate_patch.dart:283:19) #2 _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:184:12)
三 Dart中的異常處理
3.1 異常處理說明
當使用try處理異常語句時,顯示下列內容(try後可接:on/catch/finally)
A try block must be followed by an 'on', 'catch', or 'finally' clause.
Try adding either a catch or finally clause, or remove the try statement.
3.2 try…on
main() { var a = -1; try { if (a < 0) { throw ("異常"); } } on int { print("捕獲了整數型別的異常"); } on String { print("捕獲了字串型別的異常"); } print("程式完成"); }
3.3 try…catch
main() {
var a = -1;
try {
if (a < 0) {
throw ("異常");
}
} catch(ex) {
print("捕獲了異常:$ex");
}
print("程式完成");
}
3.4 try…catch…finally
main() { var a = -1; try { if (a < 0) { throw ("異常"); } } catch (ex) { print("捕獲了異常:$ex"); } finally { print("異常處理結束"); } print("程式完成"); }