-2

I just converted my code to Swift 2.0 and it converted the code beautifully.

Just one thing I am not able to understand that how to use the try-catch in my codes.

I am posting the data and getting the JSON formatted

if anything goes wrong in network then it throws error and app crashes when JSON serialisation is done. How to prevent this, my code snap is below.

do {
            json =  try! NSJSONSerialization.JSONObjectWithData(data!, options: .MutableLeaves) as? NSDictionary
        }
        catch {
            // report error
        }

It crashed in the line

 json =  try! NSJSONSerialization.JSONObjectWithData(data!, options: .MutableLeaves) as? NSDictionary

How to use catch so that it does not crash here and shows error!!!

Saty
  • 2,563
  • 3
  • 37
  • 88
  • just try not try! , try! mean crash if error ,try mean if error go to catch . you have to declare an error variable as NSError for catching the error : catch let error as NSError – kholl Jan 07 '16 at 10:30
  • 2
    Possible duplicate of [Error-Handling in Swift-Language](http://stackoverflow.com/questions/24010569/error-handling-in-swift-language) – Cristik Jan 07 '16 at 13:41

3 Answers3

1

I'm using it in my project like

do{
        if let result = try NSJSONSerialization.JSONObjectWithData(resultData, options: []) as? NSMutableDictionary{
        }
    }
    catch let error as NSError{
        print("Error : \(error)")
    }
Ankita Shah
  • 2,178
  • 3
  • 25
  • 42
0

use this syntax, and remove the "!" in the try

do {
            json =  try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableLeaves) as? NSDictionary
        }
        catch _ {
            // report error
            print("Exception")
        }
Diego
  • 2,395
  • 2
  • 21
  • 27
0

like diego said but the catch do like this to see what is the error you get in case you get one for debugging

catch let error as NSError{
    print("Error : \(error)")
    //or NSLog()
    NSLog("Error = %@",error)
}