Error Handling in Swift

By | October 1, 2016

When calling a method that may cause a failure, you normally pass it with an NSError object (as a pointer). If there is an error, the object will be set with the corresponding error. You then check if the error object is nil or not and respond to the error accordingly.
That’s how you handle errors in Swift 1.2.

try / throw / catch

In Swift 2, it comes with an exception-like model using try / throw / catch keywords. The code snippet will become this:

    let request = NSURLRequest(URL: NSURL(string:"")!)
    var response:NSURLResponse?
    var error:NSError?
    do {
        let data = try NSURLConnection.sendSynchronousRequest(request,
                                        returningResponse: &response)
        // Parse the data
    } catch {
        // handle error

Now you use do-catch statement to catch errors and handle them accordingly.
As you may notice, we’ve put a try keyword in front of the method call.
With the introduction of the new error handling model in Swift 2.0, some methods can throw errors to indicate failures. When we invoke a throwing method, you will need to put a try keyword in front of it.

Leave a Reply

Your email address will not be published. Required fields are marked *