1

Swift Errors Thrown from here are not handled

I followed the above link but i still seeing that issue. Adding code below

do {
    // print("\(v)")
    let jsonData = try NSJSONSerialization.dataWithJSONObject(["code":"102", "response":v], options: NSJSONWritingOptions.PrettyPrinted)
    let string: String! = String(data: jsonData, encoding: NSUTF8StringEncoding);
    print("\(string)")
    BonjourClient.sharedInstance.sendString(string)
}
catch let error as NSError {
    print(error)
}
Community
  • 1
  • 1
Srikanth Adavalli
  • 665
  • 1
  • 10
  • 25
  • What version of Xcode are you using? I used to see this in older versions (because the compiler didn't realize that dataWithJSONObject only throws NSErrors), but I can't reproduce it with 7.2. – Rob Napier Feb 05 '16 at 01:17
  • Hey @RobNapier Xcode Version which i am using is 7.2. – Srikanth Adavalli Feb 05 '16 at 01:20
  • The problem is that it is possible to throw errors that aren't `NSError`, and you're not handling those. I'm just surprised that I'm not seeing the error, at least in a playground. (I'd noticed earlier this week that I wasn't seeing that error in my code, which surprised me.) – Rob Napier Feb 05 '16 at 01:34

2 Answers2

2

Swift 5

enum MyError: Error {
    case somePattern
}

// … 

do {
    let jsonData = try JSONSerialization.data(withJSONObject: /*…*/)
} catch MyError.somePattern {
    print("Some specific known error type occured.")
} catch { // exhaustive. not constrained to any specific error
    print("Unexpected, not otherwise caught, error: \(error)")
}

Swift 4

enum MyError: Error {
    case somePattern
}

// … 

do {
    let jsonData = try NSJSONSerialization.dataWithJSONObject([/*…*/])
} catch MyError.somePattern {
    print("Some specific known error type occured.")
} catch { // exhaustive. not constrained to any specific error
    print("Unexpected, not otherwise caught, error: \(error)")
}

Note that error is available in the final catch clause example above.

See The Swift Programming Language Error Handling

If no pattern is matched, the error gets caught by the final catch clause and is bound to a local error constant.

marc-medley
  • 8,931
  • 5
  • 60
  • 66
1

The problem is that you missing an empty catch, and should add:


catch {
}
scorpiozj
  • 2,687
  • 5
  • 34
  • 60