Understanding Error Handling in Swift
Gain an understanding of how to trigger and handle errors gracefully within Swift code. Additionally , see how to design code to throw and catch errors to take corrective action or explain the nature of the problem encountered to the user.
In a perfect world, running code would never encounter an error. The reality, however, is that it is impossible to guarantee that an error of some form or another will not occur at some point during the execution of the app. Therefore, it is essential to ensure that the code of an app is implemented such that it gracefully handles any errors that may occur. Since the introduction of Swift 2, the task of handling errors has become much easier for the Swift developer.
This lesson will cover the handling of errors using Swift and introduce topics such as error types, throwing methods and functions, the guard
, defer
, and do-catch
statements.
Understanding error handling
No matter how carefully Swift code is designed and implemented, there will invariably be situations that are beyond the control of the app. Code that relies on an active internet connection cannot, for example, control the loss of signal or prevent the user from enabling “airplane mode.” What the code can do, however, is implement robust handling of the error (i.e., displaying a message indicating to the user that the app requires an active internet connection to proceed).
There are two sides to handling errors within Swift. The first involves triggering (or throwing) an error when the desired results are not achieved within a method. The second involves catching and handling the error after it is thrown by a method.
When an error is thrown, the error will be of a particular error type which can be used to identify the specific nature of the error and to decide on the most appropriate course of action to be taken. The error type value can be any value that conforms to the Error
protocol.
Declaring error types
As an example, consider a method that is required to transfer a 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 these possible errors could be represented within an enumeration that conforms to the Error protocol as follows:
enum FileTransferError: Error {
case noConnection
case lowBandwidth
case fileNotFound
}
Once an error type has been declared, it can be used ...