Catch Objective-C exception in Swift

devios1 picture devios1 · Jan 31, 2016 · Viewed 11.2k times · Source

I am trying to set the value of an @objc object in my Swift code using obj.setValue(value, forKey: key).

It works fine when the object has the property being set. But if it doesn't, my app crashes hard with an uncaught NSException ("class is not key value coding-compliant…").

How can I catch and absorb this exception like I can in Objective-C so as to not crash my app? I tried wrapping it in a Swift try-catch, but it complains that none of the instructions throws and does nothing.

Answer

Casey picture Casey · Feb 1, 2016

see this answer:

//
//  ExceptionCatcher.h
//

#import <Foundation/Foundation.h>    

NS_INLINE NSException * _Nullable tryBlock(void(^_Nonnull tryBlock)(void)) {
    @try {
        tryBlock();
    }
    @catch (NSException *exception) {
        return exception;
    }
    return nil;
}