Swift models recoverable failures with throws, try, and typed errors conforming to Error—unlike exceptions in Java, errors are part of the function signature and must be handled explicitly.
Defining and throwing
enum ParseError: Error {
case invalidInput
case outOfRange
}
func parse(_ text: String) throws -> Int {
guard let value = Int(text) else { throw ParseError.invalidInput }
return value
}
try, try?, try!
do {
let n = try parse("42")
print(n)
} catch {
print("failed: \(error)")
}
try? converts to optional; try! force-unwraps—avoid in production.
Important interview questions and answers
- Q: throws vs Result?
A:throwsintegrates withdo/catch;Result<Success, Failure>suits async callbacks and functional pipelines—often combined with async/await. - Q: Checked vs unchecked?
A: Swift errors are typed and propagated viatry—callers must handle or rethrow; unlike Java checked exceptions but more explicit than optional-only returns.
Self-check
- What does
try?return on failure? - How do you define a custom error type?
Pitfall: Avoid try! in production—crashes on unexpected errors like force unwrap.
Interview prep
- try? result?
Converts to optional nil on failure.
- throws vs Result?
throws integrates with do/catch; Result suits functional pipelines.