Future<void> fetchUserOrder() async {
// Imagine that this function is fetching user info but encounters a bug
try {
return Future.delayed(const Duration(seconds: 2),
() => throw Exception('Logout failed: user ID is invalid'));
} catch(e) {
// Why exception is not caught here?
print(e);
}
}
void main() {
fetchUserOrder();
print('Fetching user order...');
}
它輸出
Fetching user order...
Uncaught Error: Exception: Logout failed: user ID is invalid
這表示未捕獲例外。但是如您所見,該throw Exception子句被 try catch 包圍。
uj5u.com熱心網友回復:
try-catch 塊只會捕獲等待的Future 的例外。所以你必須await在你的代碼中使用:
Future<void> fetchUserOrder() async {
// Imagine that this function is fetching user info but encounters a bug
try {
return await Future.delayed(const Duration(seconds: 2),
() => throw Exception('Logout failed: user ID is invalid'));
} catch(e) {
// Why exception is not caught here?
print(e);
}
}
void main() {
fetchUserOrder();
print('Fetching user order...');
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/371751.html
上一篇:flutter無法將引數型別'voidFunction(String)'分配給引數型別'voidFunction(String?)?'撲騰
