I have a block of code that needs to execute 2 statements that require a try. Is it better to nest the try's and each one has their own do { } catch {}
do { try thingOne() do { try thingTwo() } catch let error as NSError { //handle this specific error } } catch let error as NSError { //handle the other specific error here }
...or wrap the try's in one do block and run them consecutively?
do { try thingOne() try thingTwo() } catch let error as NSError { //do something with this error }
The second scenario seems easier to read than the first, although will that catch
work if either of those throws an error?
I would then need to distinguish between the different errors that get thrown, unless the errors are generic enough, then it might not matter. Looked through the Apple documentation and didn't see anything regarding this.
I think second way is better
Suppose I have these two function
func thingOne() throws{ print("Thing 1") throw CustomError.Type1 } func thingTwo() throws{ print("Thing 2") throw CustomError.Type2 } enum CustomError:ErrorType{ case Type1 case Type2 }
Then I will call it like this
do { try thingOne() try thingTwo() } catch CustomError.Type1 { print("Error1") } catch CustomError.Type2{ print("Error2") } catch { print("Not known\(error) ") }
This will log
Thing 1 Error1
If thingOne()
does not throws the error,it will log
Thing 1 Thing 2 Error2
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With