Swift Error Handling

A portrait painting style image of a pirate holding an iPhone.

by The Captain

on
August 3, 2023

Tutorial: Swift Error Handling with Try, Catch, and Throw

Error handling is an essential concept in Swift programming that allows you to gracefully handle predictable errors or exceptional situations in your code. Swift provides a mechanism for error handling using the keywords try, catch, and throw.

To handle errors, you first mark a function that can potentially throw an error using the throws keyword. For example, consider a function that divides two numbers and throws an error if the divisor is zero:


func divide(_ dividend: Int, by divisor: Int) throws -> Int {
    guard divisor != 0 else {
        throw NSError(domain: "divisionError", code: 1, userInfo: [NSLocalizedDescriptionKey: "Cannot divide by zero."])
    }
    return dividend / divisor
}

In the function above, if the divisor is zero, an error is thrown using the throw keyword along with the appropriate error information.

To call a function that can throw an error, you use the try keyword. The try keyword indicates that you are aware the function may throw an error and you want to handle it accordingly. You can handle errors using a catch block. For example:


do {
    let result = try divide(10, by: 0)
    print("The result is \(result).")
} catch {
    print("An error occurred: \(error.localizedDescription)")
}

In the example above, we try to divide the number 10 by 0, which will throw an error. Inside the do block, we use the try keyword to call the divide(_:by:) function. If an error occurs, it is caught by the catch block where we can handle the error appropriately.

There are also scenarios where you may want to catch specific types of errors. You can do so by specifying the error type in the catch block. For example:


do {
    let result = try divide(10, by: 0)
    print("The result is \(result).")
} catch let error as NSError {
    print("An NSError occurred: \(error.localizedDescription)")
}

In the updated example, we catch errors of type NSError specifically, allowing us to handle them differently from other types of errors.

Error handling is crucial for writing robust and reliable code in Swift, where you can handle potential failures gracefully and provide appropriate feedback to users.

Summary: Error handling in Swift allows for graceful handling of potential errors or exceptional situations in code using the try, catch, and throw keywords.