throw, try, and catch
throw is raising your hand to say something went wrong, try is attempting something that might fail, and catch is what handles it if it does.
In this page:
Declaring and Throwing an Error
A function marked throws can use throw to raise an error instead of returning normally when something goes wrong.
Example: Declaring and Throwing an Error
enum ValidationError: Error {
case empty
}
func validate(_ text: String) throws -> String {
if text.isEmpty {
throw ValidationError.empty
}
return text
}
do {
let result = try validate("Hello")
print("Valid: \(result)")
} catch {
print("Validation failed: \(error)")
}
Login to try C/C++/Java/PHP code in the editor
Handling Multiple Error Cases
Multiple catch clauses can match specific error cases in order, similar to a switch statement, with a final unmatched catch as a fallback.
Example: Handling Multiple Error Cases
enum ValidationError: Error {
case empty
case tooShort
}
func validate(_ text: String) throws -> String {
if text.isEmpty { throw ValidationError.empty }
if text.count < 3 { throw ValidationError.tooShort }
return text
}
do {
let result = try validate("hi")
print("Valid: \(result)")
} catch ValidationError.empty {
print("Text was empty")
} catch ValidationError.tooShort {
print("Text was too short")
} catch {
print("Unknown error")
}
Login to try C/C++/Java/PHP code in the editor
Common Mistakes
- Forgetting to mark a function that can throw with
throwsin its signature -- Swift won't let youthrowfrom a non-throwing function. - Calling a throwing function without
tryin front of it; every call to a throwing function must be prefixed withtry,try?, ortry!. - Writing a
catchblock that doesn't match any specific error case; a plaincatchat the end acts as a catch-all, but a mismatched typed catch just falls through.
Chapter Summary
- A function that can fail is marked with
throwsafter its parameter list. throw someErrorraises an error, stopping normal execution of the current function.- Calling a throwing function requires
try, and the call is usually wrapped indo { } catch { }. - Multiple
catchblocks can match specific error cases, similar to a switch.
🔒
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: