You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Dart async函数中为什么这种方式无法捕获异常?

异常未被捕获的原因

async 函数中的 try/catch 仅支持捕获两类异常:

  • 函数内部同步执行代码抛出的异常
  • 被 await 关键字修饰的 Future 实例抛出的异步异常

你当前代码直接将 Future.delayed 生成的 Future 作为返回值返回,没有添加 await 修饰,这个 Future 的执行时机是在 try 块执行完成、函数已经返回之后,它内部抛出的异常不属于当前 try/catch 的捕获范围,就会变成全局未捕获异常。

修复方案

方案1:给 Future 添加 await 修饰(最常用)

不要直接返回 Future,添加 await 等待其执行完成,异常就会被当前 try/catch 捕获:

Future<void> fetchUserOrder() async {
  // 模拟该函数拉取用户信息时触发了错误
  try {
    await Future.delayed(const Duration(seconds: 2),
        () => throw Exception('Logout failed: user ID is invalid'));
  } catch(e) {
    print(e);
  }
}

void main() {
  fetchUserOrder();
  print('Fetching user order...');
}

修改后运行输出为:

Fetching user order...
Exception: Logout failed: user ID is invalid

方案2:给 Future 挂载 catchError 回调

如果必须直接返回 Future 实例,可以给它手动挂载 catchError 回调处理异常:

Future<void> fetchUserOrder() async {
  // 模拟该函数拉取用户信息时触发了错误
  try {
    return Future.delayed(const Duration(seconds: 2),
        () => throw Exception('Logout failed: user ID is invalid')).catchError((e) {
          print(e);
        });
  } catch(e) {
    print(e);
  }
}

void main() {
  fetchUserOrder();
  print('Fetching user order...');
}

运行效果和方案1一致。


内容的提问来源于stack exchange,提问作者Daniel Dai

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 08:15:04