EZ

Eduzan

Learning Hub

Eduzan
Eduzan / Swift

Swift Additional Topics

Error handling refers to the process of responding to issues that arise during the execution of a function. A function can raise an error when it encounters an exceptional condition. The error can then be caught and addressed appropriately. Essentially, error handling allows us to deal with errors gracefully without abruptly exiting the code or application.

In this explanation, we’ll focus on what happens when an error is raised versus when it is not. Below is an example of a function, canThrowAnError(), demonstrating error handling implemented outside the loop in Swift.

Example 1:

func canThrowAnError() throws {
    // This function may or may not throw an error
}

do {
    try canThrowAnError()
    // No error was thrown
}
catch {
    // An error was thrown
}

Real-world Scenario

Case 1: The function throws an error.

For example, the function startCar() will raise an error if the seatbelt is not fastened or the fuel is low. Since startCar() can throw an error, it is wrapped in a try expression. When such a function is used within a do block, any errors it throws can be caught and handled using the appropriate catch clauses.

Case 2: The function does not throw an error.

If no error is raised when the function is called, the program continues executing without interruption. However, if an error occurs, it will be matched to a specific catch clause. For instance:

  • If the error corresponds to the carError.noSeatBelt case, the blinkSeatBeltSign() function will be called.
  • If the error matches the carError.lowFuel case, the goToFuelStation(_:) function will be invoked, using the associated fuel-related details provided by the catch pattern.

Example:

func startCar() throws {
    // Logic to start the car, which may throw an error
}

do {
    try startCar()
    turnOnAC()
}
catch carError.noSeatBelt {
    blinkSeatBeltSign()
}
catch carError.lowFuel(let fuel) {
    goToFuelStation(fuel)
}

Output:

1. If no error is thrown:

  • The car starts, and the air conditioner is turned on.

2. If an error is thrown:

  • For carError.noSeatBelt, the seatbelt sign blinks.
  • For carError.lowFuel, the function goToFuelStation(_:) is executed with the relevant fuel information.
End of lesson.