【问题标题】:Errors thrown from here are not handled because the enclosing catch is not exhaustive从这里抛出的错误不会被处理,因为封闭的 catch 并不详尽
【发布时间】:2016-02-05 00:56:33
【问题描述】:

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

【问题讨论】:

  • 您使用的是什么版本的 Xcode?我曾经在旧版本中看到过这种情况(因为编译器没有意识到 dataWithJSONObject 只会抛出 NSErrors),但我无法用 7.2 重现它。
  • 嘿 @RobNapier Xcode 我正在使用的版本是 7.2。
  • 问题是有可能抛出不是NSError 的错误,而你没有处理这些错误。我很惊讶我没有看到错误,至少在操场上。 (本周早些时候我注意到我的代码中没有看到该错误,这让我感到惊讶。)

标签: json swift error-handling compiler-errors


【解决方案1】:

斯威夫特 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)")
}

斯威夫特 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)")
}

请注意,error 在上面的最终 catch 子句示例中可用。

The Swift Programming Language Error Handling

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

【讨论】:

    【解决方案2】:

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

    
    catch {
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-03-21
      • 2015-08-29
      • 1970-01-01
      • 2021-12-06
      • 1970-01-01
      • 2018-01-12
      • 1970-01-01
      相关资源
      最近更新 更多