How should I use NSSetUncaughtExceptionHandler in Swift

As of Swift 2 (Xcode 7), you can pass Swift functions/closures
to parameters taking a C function pointer. From the Xcode 7 release notes:

Native support for C function pointers: C functions that take function
pointer arguments can be called using closures or global functions,
with the restriction that the closure must not capture any of its
local context.

So this compiles and works:

func exceptionHandler(exception : NSException) {
    print(exception)
    print(exception.callStackSymbols)
}

NSSetUncaughtExceptionHandler(exceptionHandler)

Or with an “inline” closure:

NSSetUncaughtExceptionHandler { exception in
    print(exception)
    print(exception.callStackSymbols)
}

This does exactly the same as the corresponding Objective-C code:
it catches otherwise uncaught NSExceptions.
So this will be caught:

let array = NSArray()
let elem = array.objectAtIndex(99)

NOTE:- It does not catch any Swift 2 errors (from throw) or Swift runtime errors, so this is not caught:

let arr = [1, 2, 3]
let elem = arr[4]

Leave a Comment