Back to Swift Reference
🔶 Swift LanguageBeginnerSwift 2.0+ · typed throws Swift 6

Error Handling (throws, do/catch, typed throws)

Throw and catch errors, convert with try? and use Swift 6 typed throws for precise error types.

Functions marked throws can fail. Callers use try inside do/catch, try? to turn failure into nil, or try! when failure is impossible.

Swift 6 adds typed throws: throws(MyError) declares exactly which error type can be thrown, so catch blocks get a concrete type.

error-handling.swift
1enum LoginError: Error {
2    case emptyEmail
3    case wrongPassword
4}
5
6func login(email: String, password: String) throws(LoginError) -> String {
7    guard !email.isEmpty else { throw .emptyEmail }
8    guard password == "secret" else { throw .wrongPassword }
9    return "token-123"
10}
11
12do {
13    let token = try login(email: "[email protected]", password: "nope")
14    print(token)
15} catch {
16    // error is LoginError here — no casting needed
17    switch error {
18    case .emptyEmail: print("Enter an email")
19    case .wrongPassword: print("Try again")
20    }
21}

Common pitfalls

  • Do not swallow errors silently with try? in places where the user needs feedback.

Still unclear? Ask BeeAI about Error Handling (throws, do/catch, typed throws).

Get a tailored explanation, or paste your own code for a Swift 6 review. Free members get daily questions — Pro is unlimited.

Ask BeeAI

Become a Founding Pro member: unlimited BeeAI, upcoming Swift paths and every new reference entry first.

See Pro Plans