错误“调用可以抛出,但没有标记'try'并且错误不被处理” [英] Error "Call can throw, but is not marked with 'try' and the error is not handled"

查看:112
本文介绍了错误“调用可以抛出,但没有标记'try'并且错误不被处理”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我正在使用Xcode 7.1最新的测试版和swift 2.0

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

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

解决方案

Swift 2.0引入了错误处理。该错误表示 logInWithUsername:password:可能会引发错误,您必须对该错误执行某些操作。您有以下选项之一:



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

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

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

使用 code> / catch 语法来捕捉潜在错误:

  func checkUserCredentials() - > Bool {
do {
try PFUser.logInWithUsername(userName !, password:password!)
}
catch _ {
//处理错误
}

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
}


Getting an error with this piece of code "Call can throw, but is not marked with 'try' and the error is not handled"

I am using the Xcode 7.1 the latest beta and swift 2.0

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

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

解决方案

Swift 2.0 introduces error handling. The error indicates that logInWithUsername:password: can potentially throw an error, and you must do something with that error. You have one of a few options:

Mark your checkUserCredentials() functional as throws and propagate the error to the caller:

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

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

Use do/catch syntax to catch the potential error:

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

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

Use the try! keyword to have the program trap if an error is thrown, this is only appropriate if you know for a fact the function will never throw given the current circumstances - similar to using ! to force unwrap an optional (seems unlikely given the method name):

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

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

这篇关于错误“调用可以抛出,但没有标记'try'并且错误不被处理”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆