ERROR Handling in swift
Ideally, errors should never occur. File we need should always be available and networks should always be present and reliable. Unfortunately this reality is not ideal and we have to deal with the consequences. Thankfully the Swift team included a great way to handle these deviations from the ideal in Swift 2. Swift Error Handling lets us quickly and easily warn the compiler whether a function can throw an error, actually throw it, and handle it in whatever way seems appropriate.
There is one major difference between how Objective-C handles errors, and the new Swift Error Handling. If you done any work with NSError in Objective-C, be honest, have you ever given “nil” instead of an NSError pointer when you dealt with a method that could throw an error? Yeah, I thought so. In Objective-C, to PROPERLY deal with errors, you would have to do something like this:
enum FileReadingError: ErrorType
{
case FileNotFound
case InsufficientPermission
case FileCorrupted
}
func pretendToReadTestFile() throws -> NSData {
throw FileReadingError.FileNotFound
}
let data = try pretendToReadTestFile()
func getDataFromSomething() throws -> NSData {
let data = try pretendToReadTestFile()
return data
}
do {
let someData = try pretendToReadTestFile()
} catch FileReadingError.FileNotFound {
print("The file was not found.")
}
do {
let someData = try pretendToReadTestFile()
} catch {
print("Something weird happened.")
}
do {
let someData = try pretendToReadTestFile()
} catch {
print("Something weird happened.")
}
let definitelyNoData = try! pretendToReadTestFile()
//Execution was interrupted, reason: EXC_BAD_INSTRUCTION
//error: 'try!' expression unexpectedly raised an error: FileReadingError.FileNotFound
Discover more from CODE t!ps
Subscribe to get the latest posts sent to your email.