【问题标题】:Error "Call can throw, but is not marked with 'try' and the error is not handled"错误“调用可以抛出,但未标有‘try’且错误未处理”
【发布时间】:2016-01-05 00:32:58
【问题描述】:

这段代码出错 "调用可以抛出,但没有标记'try',错误未处理"

我使用的是 Xcode 7.1 最新的 beta 和 swift 2.0

func checkUserCredentials() -> Bool {
    PFUser.logInWithUsername(userName!, password: password!)

    if (PFUser.currentUser() != nil) {
        return true
    }
    return false

【问题讨论】:

  • Do { try PFUser.login ..... } catch let error as NSError { print(error.localizedDescription) }
  • 在该段中替换我的完整代码是什么?

标签: ios xcode swift parse-platform error-handling


【解决方案1】:

Swift 2.0 引入了error handling。该错误表明logInWithUsername:password: 可能会引发错误,您必须对该错误进行处理。您有以下几种选择之一:

将您的 checkUserCredentials() 功能标记为 throws 并将错误传播给调用者:

func checkUserCredentials() throws -> Bool {
    try PFUser.logInWithUsername(userName!, password: password!)

    if (PFUser.currentUser() != nil) {
        return true
    }
    return false
}

使用do/catch 语法捕获潜在错误:

func checkUserCredentials() -> Bool {
    do {
        try PFUser.logInWithUsername(userName!, password: password!)
    }
    catch _ {
        // Error handling
    }

    if (PFUser.currentUser() != nil) {
        return true
    }
    return false
}

使用 try! 关键字在抛出错误时让程序陷入困境,这仅适用于您知道在当前情况下函数永远不会抛出的事实 - 类似于使用 ! 强制展开可选(考虑到方法名称似乎不太可能):

func checkUserCredentials() -> Bool {
    try! PFUser.logInWithUsername(userName!, password: password!)

    if (PFUser.currentUser() != nil) {
        return true
    }
    return false
}

【讨论】:

  • 在我的代码中,这一切都在哪里。我对此很陌生。
  • @RobertS 答案为您提供了代码。你必须在你的PFUser.logInWithUsername 电话之前加上try。答案很好地解释了这一点。 :)
  • @RobertS 这是您提供的功能的三个不同版本,具体取决于您需要执行的操作。我建议您点击文档链接并查看详细信息。
  • @Charles A. 出色的工作。工作!谢谢!
猜你喜欢
  • 2016-02-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-08-24
  • 1970-01-01
  • 2017-11-01
  • 1970-01-01
相关资源
最近更新 更多