从这里抛出的错误不会被处理,因为封闭的捕获并不详尽

时间:2016-02-05 00:56:33

标签: json swift error-handling compiler-errors

Swift Errors Thrown from here are not handled

我按照上面的链接但我仍然看到了这个问题。添加以下代码

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)
}

2 个答案:

答案 0 :(得分:0)

问题是你错过了一个空的catch,应该添加:


catch {
}

答案 1 :(得分:0)

Swift 4

enum MyError: Error {
    case somePattern
}

… 

do {
    let jsonData = try NSJSONSerialization. …
} 
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)")
}

请注意,上面最后的error子句示例中提供了catch

请参阅The Swift Programming Language Error Handling

  

如果没有匹配的模式,则错误会被最终的catch子句捕获并绑定到本地error常量。