但没有标记为‘try’

但没有标记为‘try’

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

问题描述

这段代码出现错误调用可以抛出,但是没有用'try'标记并且错误没有被处理"

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

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

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 引入 错误处理.该错误表明 logInWithUsername:password: 可能会引发错误,您必须对该错误进行处理.您有以下几种选择之一:

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:

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

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
}

使用do/catch 语法来捕捉潜在的错误:

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
}

使用 try! 关键字让程序在抛出错误时进行陷阱,这仅适用于您知道在当前情况下函数永远不会抛出的事实 - 类似于使用 ! 强制解包一个可选的(鉴于方法名称似乎不太可能):

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’,并且错误未被处理";的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 22:57