throws and Error
Part of the Logic & Flow section of Coddy's Swift journey — lesson 44 of 56.
Swift handles errors by making functions declare that they can fail. The function body throws an error value; the caller must handle it.
An error type is anything that conforms to the built-in Error protocol. The simplest way to declare your own is with an enum:
enum InputError: Error {
case empty
case tooLong
}A throwing function uses the throws keyword in its signature and the throw statement in its body:
func validate(_ s: String) throws -> String {
if s.isEmpty { throw InputError.empty }
if s.count > 100 { throw InputError.tooLong }
return s
}You can't call a throwing function directly, the compiler forces you to handle the error. The next lesson covers how.
Challenge
EasyDefine an enum NumError: Error with two cases: negative and tooBig.
Define a throwing function doubleSafely(_ n: Int) throws -> Int that:
- Throws
.negativewhenn < 0 - Throws
.tooBigwhenn > 100 - Otherwise returns
n * 2
Read a single integer from stdin. Call doubleSafely inside a do/catch block (you'll learn the exact form next lesson; for now use this exact skeleton):
do {
let result = try doubleSafely(n)
print("ok: \(result)")
} catch NumError.negative {
print("negative")
} catch NumError.tooBig {
print("too big")
} catch {
print("unknown")
}For input 10 the output is ok: 20. For -1 it's negative. For 500 it's too big.
Cheat sheet
Define error types using an enum conforming to Error:
enum InputError: Error {
case empty
case tooLong
}Mark a function as throwing with throws and use throw to raise an error:
func validate(_ s: String) throws -> String {
if s.isEmpty { throw InputError.empty }
if s.count > 100 { throw InputError.tooLong }
return s
}Throwing functions must be called with error handling (e.g. do/catch); the compiler enforces this.
Try it yourself
let n = Int(readLine()!)!
// TODO: enum NumError: Error { case negative, tooBig }
// func doubleSafely(_ n: Int) throws -> Int { ... }
// do { let r = try doubleSafely(n); ... } catch NumError.negative { ... } ...
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Strings In Depth
Count and IndicesCase and TrimSearching in StringsSplitting and JoiningReplacing SubstringsRecap - Username Check