Handling Returning Error with Throwing Error in Swift

Tram Ho

In Swift, there are two ways to handle errors:

  • Return Value – The function returns a value like Boolean, Class, Enum, and other types.
  • do – catch statement – The function will “throw” the error. These errors are then handled by the do-catch statement:

So what’s the difference?

To answer this question, we start with the following example:
We have a car and we need to decide if it has enough gas or if the engine is overheated. And to determine the above cases, we have the following functions: driving () and temperatureChanged (: Double) .

Return value:

First, we create an enum for the EngineTemperature:

Next, we will create a struct called Car:

In Car there are two functions:

  • driving () -> Bool will return False if gas is insufficient
  • temperatureChange (: Double) → EngineTemperature will return TooHigh when the temperature is greater than 100, ABitHot when the thermogram is greater than 60 and less than 100 and Cool when less than 60.

As we can see, the return of the value is very straightforward. However, there are times when we may forget some errors when installing it. And installing too many conditional statements leads to a decrease in the readability of the code.

Use case do-catch:

First, we need to define two enums called EnginEror and EngineTemperatureError with Error Protocol:

EngineError has an error called InsufficientGas and EngineTemperatureError has 2 errors with the associated values ​​EngineTooHot and EngineABitHot.
Next we install struct Car:

Since we will “throw” the error, there is no need to return any values ​​from driving () and temperatureChange (_: Double):

This way, we can divide the code for the normal installation and the code for error handling. The code is easier to read and clear.

Advantages and disadvantages:

Return Value:

  • Advantages: Easy to install
  • Disadvantage: Not suitable when we need more return information.

Do-catch:

  • Advantages: Allows us to have more complex error structures. Increased code clarity.
  • Disadvantage: Complicated.

In the above example, if we just want to know if there is enough gas to continue driving, returning a Bool is sufficient. However, when we want to know the engine’s temperature, and see if it gets overheated or normal temperature it is more appropriate to “throw” about an error.

Summary:

If we want to get simple value from a function then use Return Value. If you want something more than usual, perhaps using Do-catch will be more suitable.

Reference : https://medium.com/flawless-app-stories/returning-error-vs-throwing-error-in-swift-8d3657e1330d

Share the news now

Source : Viblo