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

Dart函数执行catch块后不再继续,原因是什么?

问题原因及解决办法

你遇到的情况不是代码在catch块后停止运行,而是后续代码触发了未被捕获的空值异常,直接导致函数终止。

具体原因分析

当client.post抛出错误时,try块里的response = await ...不会执行,response始终是初始的null值。但你在后续的log方法里用了response!强制解包null,这会触发空值异常,而这个异常没有被任何catch块捕获,所以函数直接崩溃,看起来像是代码没走到后面。

解决思路

方案1:避免强制解包,先做null判断

修改log相关代码,先确认response不为null再执行:

if (response != null) {
  log(url: url, type: 'POST', body: body as String?, response: response);
} else {
  debugPrint('请求失败,无响应数据');
}

方案2:在catch块里提前终止逻辑

如果请求失败后不需要执行后续的log和parse逻辑,可以在catch里直接抛出异常或返回错误响应:

catch (_) {
  debugPrint('test');
  // 重新抛出异常,让上层调用方处理
  rethrow;
  // 或者返回一个自定义的错误响应
  // return http.Response('请求失败', 500);
}

方案3:给response设置默认值

初始化时给response一个默认的错误响应对象(根据业务需求调整),避免null:

http.Response response = http.Response('初始状态', 0);

内容的提问来源于stack exchange,提问作者Raymond Holmboe

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 04:40:24