【问题标题】:Why exception is not caught this way in async function in Dart?为什么在 Dart 的异步函数中没有以这种方式捕获异常?
【发布时间】:2022-01-08 18:46:38
【问题描述】:
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 包围。

【问题讨论】:

标签: dart async-await


【解决方案1】:

try-catch 块只会捕获 awaited 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...');
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-12-11
    • 1970-01-01
    • 2021-01-15
    • 2020-12-10
    • 2011-04-12
    • 2021-12-26
    • 2010-12-24
    相关资源
    最近更新 更多