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?
2
Answers
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:
If you have no
catch
logic inthowingFunc1
, you can remove thedo/catch
, and thetry
will throw to the caller automatically.You can re-throw the error in the catch block in
throwingFunc1
:Then the catch block of something like this would be executed:
Note that the catch block pattern can be omitted: