[英]Dart: can't handle exceptions using the try catch block
我正在學習dart。我想不通為什么下面的dart代碼無法處理異常。 我在下面做錯了什么?:
void main() {
print(1);
try {
File file = File('random_path.txt');
print(2);
var contents = file.readAsString();
print(3);
contents.then((value) => print(value));
print(4);
} on FileSystemException catch (e) {
print(5);
print(e);
} catch (e) {
print(6);
print(e);
} finally {
print(7);
}
print(8);
}
文件random_path.txt
不存在。 我期待on FileSystemException catch(e)
捕捉並打印e
。 但事實並非如此。 這是 output:
1
2
3
4
7
8
Unhandled exception:
FileSystemException: Cannot open file, path = 'random_path.txt' (OS Error: No such file or directory, errno = 2)
#0 _File.open.<anonymous closure> (dart:io/file_impl.dart:356:9)
<asynchronous suspension>
您需要處理contents
future 報告的錯誤,並轉發給then
返回的 future。
這意味着要么自己添加錯誤處理程序:
contents.then(print).catchError((e, s) {
print("Future error: $e\n$s");
}); // Catches errors from `contents` or thrown by `print`.
// or
contents.then(print, onError: (e, s) {
print("Future error: $e\n$s");
}); // Won't catch error thrown by `print`.
或者使用async
function 來處理未來的await
,這是推薦的方法:
void main() async { // <- marked as async so you can use `await`.
print(1);
try {
File file = File('random_path.txt');
print(2);
Future<String> contents = file.readAsString();
print(3);
var value = await contents; // <- await gets value, or rethrows error
print(value);
print(4);
} on FileSystemException catch (e) {
print(5);
print(e);
} catch (e) {
print(6);
print(e);
} finally {
print(7);
}
print(8);
}
通常,始終使用async
函數並await
處理期貨。 使用.then
API 主要是針對集成不同異步計算的低級代碼,一次要等待不止一件事情。 它是內部用於構建基於 API 的良好Future
的內容,您可以await
它。 你應該盡可能await
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.