Open In App

Swift – Error Handling

Last Updated : 06 Jun, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

Error handling is a response to the errors faced during the execution of a function. A function can throw an error when it encounters an error condition, catch it, and respond appropriately. In simple words, we can add an error handler to a function, to respond to it without exiting the code or the application. 

Here we will be discussing outputs retained when an error is thrown and not. The following is an example of a function canThrowAnError() with an error handler 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 
}

Remember throws is a keyword that indicates that the function can throw an error when called. Since it can throw an error, we need to add the try keyword in the beginning when the function is called. Errors are automatically propagated out of their current scopes unless handled by the catch clause do propagate the errors to one or more catch  clauses.

Real-world scenario

Case 1: It will throw an error: If the function will throw an error if the seat belt is not fastened or if the fuel is low. Because startCar() can throw an error, the function call is wrapped in a try expression. When a function is wrapped into a do function, it will be propagated to the provided clauses if any errors are thrown.

Case 2: It will not throw an error: If the function is called. If an error is thrown, and it matches the carError.noSeatBelt case, then the blinkSeatBeltSign() function will be called. If an error is thrown, and it matches the carError.lowFuel case, then the goToFuelStation(_:) function is called with the associated [String] value captured by the catch pattern.  

Let us now demonstrate the above case in the same programming language:

Example 2:

func startCar() throws 
 { 
   // Insert the body of the function here  
}

do 
{ 
 try 
 startCar() 

 turnOnAC() 
} 

catch carError.noSeatBelt 
{
 blinkSeatBeltSign() 
} 

catch carError.lowFuel(let fuel) 
{ 
 goToFuelStation(fuel) 
}

Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads