Error Handling

Declaring Error Types:

As an example, consider a method that is required to transfer file to a remote server. Such a method might fail to transfer the file for a variety of reasons such as there being no network connection, the connection being too slow or the failure to find the file to be transferred. All the possible error could be represented within an enumeration that conforms to the Errir protocol as follows:

enum FileTransferError: Error {
    case noConnection
    case lowBandWidth
    case fileNotFound
}

One an error type has been declared, it can be used within a method when throwing errors.

Throwing an Error:

    func transferFile() throws {
        guard connectionOK else {
            throw FileTransferError.noConnection
        }
        guard connectionSpeed>30 else {
            throw FileTransferError.lowBandWidth
        }
        guard fileFound else {
            throw FileTransferError.fileNotFound
        }
        
    }
    
    func sendFile() -> String {
        
//        defer {
//            removeTmpFiles()
//            closeConnection()
//        }
        
        do {
            try transferFile()
        }catch FileTransferError.noConnection {
            return "No Network connection"
        }catch FileTransferError.lowBandWidth {
            return "File Transfer Speed to low"
        }catch FileTransferError.fileNotFound {
            return "File Not Found"
        }
        catch {
            return "Unknown Error"
        }
        
        return "Successfully transfer"
    }

Error handling is an essential part of creating robust and reliable iOS apps. Since the introduction of Swift 2 it is now much easier to both trigger and handle errors. Error types are created using values that conform to the Error protocol and are most commonly implemented as enumerations. Methods and functions that throw errors are declared as such using the throws keyword. The guard and throw statements are used within the body of these methods or functions to throw errors based on the error type.

A throwable method or function is called using the try statement which must be encapsulated within a do-catch statement. A do-catch statement consists of an exhaustive list of catch pattern constructs, each of which contains the code to be executed in the event of a particular error being thrown. Cleanup tasks can be defined to be executed when a method returns through the use of the defer statement.

References:  Neil Smyth

Github Repo: https://github.com/Joynal279/ErrorHandling

205 thoughts on “Error Handling

Leave a Reply