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

17,376

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
}
Share:
17,376
Robert S
Author by

Robert S

Updated on June 05, 2022

Comments

  • Robert S
    Robert S almost 2 years

    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