Swift Error Handling with Do-Catch Example

1. Introduction

Error handling is a crucial component in developing robust applications. Swift provides a powerful way to handle runtime errors using the do-catch syntax, combined with the throw, throws, and try keywords. It allows developers to handle recoverable errors gracefully, ensuring that the application does not crash unexpectedly.

2. Source Code Example

// Defining an enum that conforms to the Error protocol to represent possible errors
enum VendingMachineError: Error {
    case invalidSelection
    case insufficientFunds(coinsNeeded: Int)
    case outOfStock

// A function that can throw an error, denoted by 'throws'
func purchaseSnack(named name: String) throws {
    switch name {
    case "Chips":
        throw VendingMachineError.outOfStock
    case "Soda":
        throw VendingMachineError.insufficientFunds(coinsNeeded: 5)
        throw VendingMachineError.invalidSelection

do {
    try purchaseSnack(named: "Chips")
    print("Purchase successful!")
} catch VendingMachineError.invalidSelection {
    print("Invalid Selection.")
} catch VendingMachineError.insufficientFunds(let coinsNeeded) {
    print("Insufficient funds. Please insert an additional \(coinsNeeded) coins.")
} catch VendingMachineError.outOfStock {
    print("Item out of stock.")
} catch {
    print("Unexpected error: \(error).")


Item out of stock.

3. Step By Step Explanation

1. We define an enumeration VendingMachineError that conforms to the Error protocol. This enumeration represents different types of errors that can occur.

2. We declare a function purchaseSnack(named:) that can throw errors. The throws keyword in the function signature indicates that this function can throw one or more of the errors defined in the VendingMachineError enum.

3. Inside the function, based on the input snack name, we simulate different error scenarios by using the throw keyword.

4. The do-catch block is used to catch and handle errors. We use the try keyword before the call to purchaseSnack(named:) to indicate that the function can throw an error.

5. If an error is thrown, the code immediately jumps to the catch blocks. Each catch block handles a specific error scenario.

6. The last catch block without a specific error type acts as a catch-all to handle any unexpected errors.