Catching Objective-C exceptions

When C++ is enabled it seems it’s not possible to catch Objective-C exceptions in Swift. I get:

Swift runtime failure: unhandled C++ / Objective-C exception

I have an Objective-C helper that wraps catching exceptions with a Swift function that throws.

Is this no longer possible? Some older APIs throw exceptions, like NSFileHandle and NSPredicate still.

I remember seeing it here that this pattern is not safe, with the alternatives suggested to catch obj-c call exceptions directly in obj-c without involving swift.

// some obj-c call wrapper:
-(BOOL)callWrapper:(...)params error:(NSError**)error {
    @try {
        // some call here known to throw Obj-C exceptions
        call(params);
        return YES;
    } catch (NSException *exception) {
        *error = ...
        return NO;
    }
}

and then call this "call" from Swift - that's safe.

Even better if you know the individual call behaviour: e.g. if it throws on, say, index out of range - validate index first in your wrapper and when it's invalid return an error right away without calling the underlying method.

5 Likes

Catching Objective-C exceptions has never been allowed in Swift.

The NSFileHandle methods that throw exceptions seem to all be deprecated now, in favor of methods that have an explicit error parameter (which are imported into Swift as throwing methods).

You can find more information about interoperability with Objective-C errors and exceptions here:

1 Like