Error-Handling in Swift-Language Error-Handling in Swift-Language swift swift

Error-Handling in Swift-Language


Swift 2 & 3

Things have changed a bit in Swift 2, as there is a new error-handling mechanism, that is somewhat more similar to exceptions but different in detail.

1. Indicating error possibility

If function/method wants to indicate that it may throw an error, it should contain throws keyword like this

func summonDefaultDragon() throws -> Dragon

Note: there is no specification for type of error the function actually can throw. This declaration simply states that the function can throw an instance of any type implementing ErrorType or is not throwing at all.

2. Invoking function that may throw errors

In order to invoke function you need to use try keyword, like this

try summonDefaultDragon()

this line should normally be present do-catch block like this

do {    let dragon = try summonDefaultDragon() } catch DragonError.dragonIsMissing {    // Some specific-case error-handling} catch DragonError.notEnoughMana(let manaRequired) {    // Other specific-case error-handlng} catch {    // Catch all error-handling}

Note: catch clause use all the powerful features of Swift pattern matching so you are very flexible here.

You may decided to propagate the error, if your are calling a throwing function from a function that is itself marked with throws keyword:

func fulfill(quest: Quest) throws {    let dragon = try summonDefaultDragon()    quest.ride(dragon)} 

Alternatively, you can call throwing function using try?:

let dragonOrNil = try? summonDefaultDragon()

This way you either get the return value or nil, if any error occurred. Using this way you do not get the error object.

Which means that you can also combine try? with useful statements like:

if let dragon = try? summonDefaultDragon()

or

guard let dragon = try? summonDefaultDragon() else { ... }

Finally, you can decide that you know that error will not actually occur (e.g. because you have already checked are prerequisites) and use try! keyword:

let dragon = try! summonDefaultDragon()

If the function actually throws an error, then you'll get a runtime error in your application and the application will terminate.

3. Throwing an error

In order to throw an error you use throw keyword like this

throw DragonError.dragonIsMissing

You can throw anything that conforms to ErrorType protocol. For starters NSError conforms to this protocol but you probably would like to go with enum-based ErrorType which enables you to group multiple related errors, potentially with additional pieces of data, like this

enum DragonError: ErrorType {    case dragonIsMissing    case notEnoughMana(requiredMana: Int)    ...}

Main differences between new Swift 2 & 3 error mechanism and Java/C#/C++ style exceptions are follows:

  • Syntax is a bit different: do-catch + try + defer vs traditional try-catch-finally syntax.
  • Exception handling usually incurs much higher execution time in exception path than in success path. This is not the case with Swift 2.0 errors, where success path and error path cost roughly the same.
  • All error throwing code must be declared, while exceptions might have been thrown from anywhere. All errors are "checked exceptions" in Java nomenclature. However, in contrast to Java, you do not specify potentially thrown errors.
  • Swift exceptions are not compatible with ObjC exceptions. Your do-catch block will not catch any NSException, and vice versa, for that you must use ObjC.
  • Swift exceptions are compatible with Cocoa NSError method conventions of returning either false (for Bool returning functions) or nil (for AnyObject returning functions) and passing NSErrorPointer with error details.

As an extra syntatic-sugar to ease error handling, there are two more concepts

  • deferred actions (using defer keyword) which let you achieve the same effect as finally blocks in Java/C#/etc
  • guard statement (using guard keyword) which let you write little less if/else code than in normal error checking/signaling code.

Swift 1

Runtime errors:

As Leandros suggests for handling runtime errors (like network connectivity problems, parsing data, opening file, etc) you should use NSError like you did in ObjC, because the Foundation, AppKit, UIKit, etc report their errors in this way. So it's more framework thing than language thing.

Another frequent pattern that is being used are separator success/failure blocks like in AFNetworking:

var sessionManager = AFHTTPSessionManager(baseURL: NSURL(string: "yavin4.yavin.planets"))sessionManager.HEAD("/api/destoryDeathStar", parameters: xwingSquad,    success: { (NSURLSessionDataTask) -> Void in        println("Success")    },    failure:{ (NSURLSessionDataTask, NSError) -> Void in        println("Failure")    })

Still the failure block frequently received NSError instance, describing the error.

Programmer errors:

For programmer errors (like out of bounds access of array element, invalid arguments passed to a function call, etc) you used exceptions in ObjC. Swift language does not seem to have any language support for exceptions (like throw, catch, etc keyword). However, as documentation suggests it is running on the same runtime as ObjC, and therefore you are still able to throw NSExceptions like this:

NSException(name: "SomeName", reason: "SomeReason", userInfo: nil).raise()

You just cannot catch them in pure Swift, although you may opt for catching exceptions in ObjC code.

The questions is whether you should throw exceptions for programmer errors, or rather use assertions as Apple suggests in the language guide.


Update June 9th 2015 - Very important

Swift 2.0 comes with try, throw, and catch keywords and the most exciting is:

Swift automatically translates Objective-C methods that produce errors into methods that throw an error according to Swift's native error handling functionality.

Note: Methods that consume errors, such as delegate methods or methods that take a completion handler with an NSError object argument, do not become methods that throw when imported by Swift.

Excerpt From: Apple Inc. “Using Swift with Cocoa and Objective-C (Swift 2 Prerelease).” iBooks.

Example: (from the book)

NSFileManager *fileManager = [NSFileManager defaultManager];NSURL *URL = [NSURL fileURLWithPath:@"/path/to/file"];NSError *error = nil;BOOL success = [fileManager removeItemAtURL:URL error:&error];if (!success && error){    NSLog(@"Error: %@", error.domain);}

The equivalent in swift will be:

let fileManager = NSFileManager.defaultManager()let URL = NSURL.fileURLWithPath("path/to/file")do {    try fileManager.removeItemAtURL(URL)} catch let error as NSError {    print ("Error: \(error.domain)")}

Throwing an Error:

*errorPtr = [NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorCannotOpenFile userInfo: nil]

Will be automatically propagated to the caller:

throw NSError(domain: NSURLErrorDomain, code: NSURLErrorCannotOpenFile, userInfo: nil)

From Apple books, The Swift Programming Language it's seems errors should be handle using enum.

Here is an example from the book.

enum ServerResponse {    case Result(String, String)    case Error(String)}let success = ServerResponse.Result("6:00 am", "8:09 pm")let failure = ServerResponse.Error("Out of cheese.")switch success {case let .Result(sunrise, sunset):    let serverResponse = "Sunrise is at \(sunrise) and sunset is at \(sunset)."case let .Error(error):    let serverResponse = "Failure...  \(error)"}

From: Apple Inc. “The Swift Programming Language.” iBooks. https://itun.es/br/jEUH0.l

Update

From Apple news books, "Using Swift with Cocoa and Objective-C". Runtime exceptions not occur using swift languages, so that's why you don't have try-catch. Instead you use Optional Chaining.

Here is a stretch from the book:

For example, in the code listing below, the first and second lines are not executed because the length property and the characterAtIndex: method do not exist on an NSDate object. The myLength constant is inferred to be an optional Int, and is set to nil. You can also use an if–let statement to conditionally unwrap the result of a method that the object may not respond to, as shown on line three

let myLength = myObject.length?let myChar = myObject.characterAtIndex?(5)if let fifthCharacter = myObject.characterAtIndex(5) {    println("Found \(fifthCharacter) at index 5")}

Excerpt From: Apple Inc. “Using Swift with Cocoa and Objective-C.” iBooks. https://itun.es/br/1u3-0.l


And the books also encourage you to use cocoa error pattern from Objective-C (NSError Object)

Error reporting in Swift follows the same pattern it does in Objective-C, with the added benefit of offering optional return values. In the simplest case, you return a Bool value from the function to indicate whether or not it succeeded. When you need to report the reason for the error, you can add to the function an NSError out parameter of type NSErrorPointer. This type is roughly equivalent to Objective-C’s NSError **, with additional memory safety and optional typing. You can use the prefix & operator to pass in a reference to an optional NSError type as an NSErrorPointer object, as shown in the code listing below.

var writeError : NSError?let written = myString.writeToFile(path, atomically: false,    encoding: NSUTF8StringEncoding,    error: &writeError)if !written {    if let error = writeError {        println("write failure: \(error.localizedDescription)")    }}

Excerpt From: Apple Inc. “Using Swift with Cocoa and Objective-C.” iBooks. https://itun.es/br/1u3-0.l


There are no Exceptions in Swift, similar to Objective-C's approach.

In development, you can use assert to catch any errors which might appear, and need to be fixed before going to production.

The classic NSError approach isn't altered, you send an NSErrorPointer, which gets populated.

Brief example:

var error: NSError?var contents = NSFileManager.defaultManager().contentsOfDirectoryAtPath("/Users/leandros", error: &error)if let error = error {    println("An error occurred \(error)")} else {    println("Contents: \(contents)")}