Search code examples
swiftexceptionswift2nsexception

Catch Objective-C exception in Swift


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.


Solution

  • 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;
    }