Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I handle consecutive multiple try's in swift 2.0

Tags:

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.

like image 426
bolnad Avatar asked Dec 08 '15 03:12

bolnad


1 Answers

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 
like image 151
Leo Avatar answered Nov 14 '22 23:11

Leo