AnyCompiler

Error Handling, and a Closing Look

A function that can fail is marked throws, and signals failure by throwing a value conforming to the Error protocol — typically an enum, as below. Calling a throwing function requires try, and a do block with a matching catch handles the error if one is actually thrown.

enum MathError: Error {
    case divideByZero
}
func safeDivide(_ a: Int, _ b: Int) throws -> Int {
    if b == 0 {
        throw MathError.divideByZero
    }
    return a / b
}
do {
    let result = try safeDivide(10, 0)
    print(result)
} catch {
    print("Caught: \(error)")
}
Output
Caught: divideByZero

The plain catch above catches any Error without binding it to a named pattern first, and error is an implicit name Swift provides inside that block — similar in spirit to Java's checked exceptions or Kotlin's try/catch, but requiring the throws keyword on the function signature itself, right alongside its return type.

That's the foundation of Swift: optionals enforced by the type system instead of discovered at runtime, structs as the default value-type choice (with mutating marking the methods allowed to change one), property observers and computed properties for reacting to or deriving state, protocols for lightweight shared behavior across unrelated types, enums that carry real data per case, and closures and extensions for writing concise, expressive code. From here, the best next step is practice — pick a small program and build it, leaning on the compiler's static type checking (and its optionals in particular) to catch mistakes as you go.

Practice exercise

Define an enum MathError: Error with case divideByZero. Write a function safeDivide(_ a: Int, _ b: Int) -> Int that uses do/try/catch internally: it throws MathError.divideByZero when b is 0 (caught and returning 0), otherwise returns a / b. Print safeDivide(10, 0).

← GenericsMore lessons coming soon