do try catch swift 2

随声附和 提交于 2019-12-08 07:46:48

问题


HI i am a little confused about how to transfer if_else error handling to do try catch successfully.

Here is my code.

let error : NSError?
if(managedObjectContext!.save()) {
    NSNotificationCenter.defaultCenter().postNotificationName("updateUndoState", object: nil)    
    if error != nil {
       print(error?.localizedDescription)
    }
}
else {
    print("abort")
    abort()
}

and now i converted to swift 2.0 like this

do {
   try managedObjectContext!.save()
}
catch {
     NSNotificationCenter.defaultCenter().postNotificationName("updateUndoState", object: nil)
     print((error as NSError).localizedDescription)
}

I am confused about where to print abort and do the abort() function

Any idea~? Thanks a lot


回答1:


Rewriting your code to work the same as your original code

do {
   try managedObjectContext!.save()

   //this happens when save did pass
   NSNotificationCenter.defaultCenter().postNotificationName("updateUndoState", object: nil)    

   //this error variable has nothing to do with save in your original code
   if error != nil {
       print(error?.localizedDescription)
   }
}
catch {
   //this happens when save() doesn't pass
   abort()
}

what you probably want to write is the following:

do {
   try managedObjectContext!.save()

   //this happens when save did pass
   NSNotificationCenter.defaultCenter().postNotificationName("updateUndoState", object: nil)    
}
catch let saveError as NSError {
   //this happens when save() doesn't pass
   print(saveError.localizedDescription)
   abort()
}



回答2:


Everything within do {} is good, everything within catch {} is bad

do {
   try managedObjectContext!.save()
   NSNotificationCenter.defaultCenter().postNotificationName("updateUndoState", object: nil)
}
catch let error as NSError {
     print(error.localizedDescription)
     abort()
}

use either the error handling or the abort() statement



来源:https://stackoverflow.com/questions/32910626/do-try-catch-swift-2

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!