Swift Error Handling
Errors are types that conform to Error. Functions that can fail are marked throws and called with try inside do catch. try? returns nil on failure.
Example
enum MathError: Error { case divideByZero }
func div(_ a: Int, _ b: Int) throws -> Int {
if b == 0 { throw MathError.divideByZero }
return a / b
}
do { print(try div(6, 3)); print(try div(1, 0)) } catch { print("error: \(error)") }
print(try? div(1, 0) as Any)Exercise
Mark a function that can fail.
func f() {}
Quiz Test
These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.