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

Swift中如何嵌套抛出函数并触发两层catch逻辑?

解决Swift中多层catch块触发问题

问题根源

当前代码存在两个关键问题导致外层catch无法触发:

  • throwingFunc1内部的do-catch已经捕获并处理了throwingFunc2的异常,没有将异常向上传递给调用者
  • 外层调用throwingFunc1时未使用try关键字,无法触发外层的do-catch捕获逻辑

调整后的代码结构

要让两个catch块都执行,需在内部catch处理完自定义逻辑后重新抛出异常,同时确保外层调用时使用try:

func throwingFunc1(_ par: Int) throws -> Int {
    do {
        let model = try throwingFunc2(par: "hello")
        return model // 根据实际业务返回对应值
    } catch let err {
        print("内层catch执行:\(err)")
        // 处理完内层逻辑后,重新抛出异常让外层catch捕获
        throw err
    }
}

func throwingFunc2(par: String) throws -> Int {
    // 模拟抛出异常的示例逻辑,可替换为实际业务代码
    throw NSError(domain: "TestError", code: 1001, userInfo: [NSLocalizedDescriptionKey: "测试异常"])
}

// 外层调用
do {
    let m = try throwingFunc1(2)
    print("正常返回值:\(m)")
} catch let error {
    print("外层catch执行:\(error)")
}

执行逻辑说明

  1. 当throwingFunc2抛出异常时,throwingFunc1内部的do-catch会先捕获异常,执行自定义处理逻辑(比如打印异常信息)
  2. 通过throw err将异常重新抛出,传递给throwingFunc1的调用者
  3. 外层的do-catch捕获到该异常,执行对应的处理逻辑

这样就实现了两个catch块依次执行对应逻辑的需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 20:40:48