Robert S
Robert S

Reputation: 193

Error "Call can throw, but is not marked with 'try' and the error is not handled"

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

enter image description here

Upvotes: 2

Views: 18097

Answers (1)

Charles A.
Charles A.

Reputation: 11123

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
}

Upvotes: 13

Related Questions