Home > Back-end >  How to write throwing function inside throwing function such that both do/catch logic works?
How to write throwing function inside throwing function such that both do/catch logic works?

Time:09-14

Edit: What I am asking is if I want to write logic to both the catch block i.e one while calling throwingFunc1 and while calling throwingFunc2. How to do structure the code.

For example:

func throwingFunc1(_ par: Int) throws -> Int {
  do {
    let model = try throwingFunc2(par: "hello")
   } catch let err {
    print(err)
    // reaching here.
   }
 }

func throwingFunc2(par: String) throws -> Int {
    //return something
 }

Now what I want here is that, when I call throwingFunc1, inside a do-catch block, the catch block is not being called. Something like this:

do {
   let m = throwingFunc1(2)
  } catch let error {
   //Not reaching here.
 }

How to structure this code such that both catch block is triggered in case throwingFunc2 sends error?

CodePudding user response:

You need to re-throw the error if you want the caller to see it. Currently you're handling the error, so it is not re-thrown. To rethrow:

func throwingFunc1(_ par: Int) throws -> Int {
  do {
    let model = try throwingFunc2(par: "hello")
   } catch let err {
    print(err)
    throw err // <---- re-throw the error.
   }
 }

If you have no catch logic in thowingFunc1, you can remove the do/catch, and the try will throw to the caller automatically.

func throwingFunc1(_ par: Int) throws -> Int {
    let model = try throwingFunc2(par: "hello") // throws on failure
 }

CodePudding user response:

You can re-throw the error in the catch block in throwingFunc1:

func throwingFunc1(_ par: Int) throws -> Int {
    do {
        let model = try throwingFunc2(par: "hello")
    } catch let err {
        print(err)
        throw err
    }
}

Then the catch block of something like this would be executed:

do {
    let int = try throwingFunc1(1)
} catch {
    // ...
}

Note that the catch block pattern can be omitted:

catch {
    print(error)
    throw error
}
  • Related