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.
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.
Related topics
Represent a value that may be missing, and unwrap it safely with if let, guard let and ??.
Model a fixed set of states — each carrying its own data — and handle them exhaustively with switch.
Write asynchronous code that reads top-to-bottom, with errors handled by normal try/catch.
Become a Founding Pro member: unlimited BeeAI, upcoming Swift paths and every new reference entry first.
See Pro Plans