Thuta Learning
AdvancedProgrammingbeginner

Error Handling

Relax. We'll talk through this in plain words — no textbook voice.

Any app can run into runtime issues — a missing file, a failed network request, a failed payment, bad input. Swift lets you handle errors properly with throw, throws, do-catch, try.

swift
enum LoginError: Error {
    case emptyUsername
    case wrongPassword
}

func login(username: String, password: String) throws {
    if username.isEmpty {
        throw LoginError.emptyUsername
    }

    if password != "123456" {
        throw LoginError.wrongPassword
    }

    print("Login success")
}

do {
    try login(username: "sai", password: "wrong")
} catch LoginError.emptyUsername {
    print("Username is required")
} catch LoginError.wrongPassword {
    print("Password is incorrect")
} catch {
    print("Something went wrong")
}

login function is marked throws since it can fail. Calling it requires try, and if it fails you land in one of the catch blocks.

You should see
Password is incorrect

Easy traps

  • Calling a function that needs try without wrapping it in do-catch can cause a compile error.
Error Handling | Thuta Learning