Error Handling Example in Swift

Error handling is the process of responding to and recovering from error conditions in your mobile app.
Some operations aren’t guaranteed to always complete execution or produce a useful output. When an operation fails, it’s often useful to understand what caused the failure, so that your code can respond accordingly.

Handle Error with Do, Try and Catch

As an example, consider the task of parsing JSON data into an Array object with the help of – do, try, and catch.

The code that might throw an error is surrounded by the do { }. A method that might throw an error is marked with the “try”.

do {
     // Convert JSON Object received from server side into Swift NSArray.
     // Note the use "try"
     if let convertedJsonIntoArray = try JSONSerialization.JSONObjectWithData(data!, options: []) as? NSArray {
 } catch let error as NSError {

For more Swift code examples and tutorials, please check the Swift Code Examples page on this website.

Leave a Reply

Your email address will not be published.