Swift Error Handling

Swift Error Handling

Written By: Debasis Das (24-Jan-2016)

Swift Error Handling
Error Handling is the process of responding and recovering from an error condition.
When a function or method fails, it is useful to understand what caused the failure and accordingly act towards providing a alternate solution or providing an informative alert to the end user.

Some of the error scenarios can be as follows

  • Trying to access an object at an non existing index in an array or set
  • Divide by 0 Scenario
  • File not found
  • Incorrect format of a file
  • Incorrect level of access for a file
  • Connection drop
  • etcIn this tutorial we will create a couple of error conditions and will demonstrate how to handle it

Sample Code

//  AppDelegate.swift
//  Swift Error Handling
//  Created by Debasis Das on 24-Jan-2016.
//  Copyright © 2015 Knowstack. All rights reserved.

import Cocoa

@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {

    @IBOutlet weak var window: NSWindow!
    
//Representing Errors
    /*
        We can use Swift Enumerations for modelling a group of related error conditions.
        In Swift, errors are represented by values of types conforming to the ErrorType protocol
    */

    /*
        In the examples given below we have modelled two error types
        DivisionError
        FileError to handle
            - Invalid File Path or FileNotFound
            - Invalid File Type (to handle expected file types
            - Invalid File Encoding
    
    */
    
    enum DivisionError: ErrorType {
        
        case ByZero
    }
    
    enum FileError: ErrorType {
        
        case InvalidFilePath
        
        case InvalidFileType(expectedFileType:String)
        
        case InvalidFileEncoding
    }

    func applicationDidFinishLaunching(aNotification: NSNotification) {
        errorHandlingTest2()
        errorHandlingTest1()
    }

    
    func applicationWillTerminate(aNotification: NSNotification) {

    }
    
    //Error Handling Test 1
    func errorHandlingTest1(){
        let dataURL:NSURL = NSURL(string: "http://www.knowstack.com/webtech/charts_demo/data.json")!
        var data = ""
        
        do
        {
            data = try readFileFromURL(dataURL)
        }
        catch let error as NSError{
            print("The error in the catch block is \(error)")
        }
        catch
        {
            print("Catch Block")
        }
        
        print("data is \(data)")
        
    }
    
    /*
    While trying to read a file, the following error might happen
    - The file does not exist at the file path or the file path is insecure
    - The file type is not as expected
    - The file encoding is not as expected.
    etc
    */
    
    /*
    NOTE: To indicate that a method/function can throw an error , we need to indicate by using the throws statement in the function as given below
    func readFileFromURL(fileUrl:NSURL) throws ->String
    */
    func readFileFromURL(fileUrl:NSURL) throws ->String {
        
        print(fileUrl)
        
        var dataString = ""
        
        do
        {
            if (fileUrl.pathExtension != "json")
            {
                throw FileError.InvalidFileType(expectedFileType: "json")
            }
            
            try dataString = String(contentsOfURL: fileUrl)

            if dataString.isEmpty
            {
                //String is nil throw an exception
                throw FileError.InvalidFilePath
            }
            
            //if dataString encoding is not of the desired type
            //{
                //Throw invalid encoding error
            //}
        }
        catch FileError.InvalidFilePath
        {
            print("The Invalid File Path was thrown and was caught here")
        }
        catch FileError.InvalidFileType(let fileType)
        {
            print("The expected file type is \(fileType)")
            throw FileError.InvalidFileType(expectedFileType: "json")
        }
        catch FileError.InvalidFileEncoding
        {
            print("Entering the InvalidFileEncoding catch block")
        }
        catch
        {
            print("Entering the final catch block, Everything else gets caught here")
        }
        
        return dataString
    }
    

    //Error Handling test 2
    //Simple try catch block
    func errorHandlingTest2(){
        var someValue = 0
        do
        {
            try someValue = divideByZero(100,val2:0)
        }
        catch let error as NSError 
        {
            print(error)
        }
        catch
        {
            print("The divide by 0 should get caught here")
        }
        print(someValue)
    }
    
    func divideByZero(val1:Int, val2:Int) throws ->Int {
        guard val2 != 0 else{
            //fatalError("Division by zero")
            //throw DivisionError.ByZero
            let dict = ["errorType":"Fatal Error","message":"You are attempting a divide by zero"]
            let error = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict as [NSObject : AnyObject])
            throw error
        }
        return val1 / val2
    }
}
Posted in Swift Tagged with: , , ,

Leave a Reply

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

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

Recent Posts


Hit Counter provided by technology news