Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 350
devios1 Avatar asked Jan 31 '16 21:01

devios1


People also ask

What is NSException in Swift?

An object that represents a special condition that interrupts the normal flow of program execution.

Can I use Objective-C in Swift?

You can use Objective-C and Swift files together in a single project, no matter which language the project used originally. This makes creating mixed-language app and framework targets as straightforward as creating an app or framework target written in a single language.

Do try catch Objective-C?

Exception handling is made available in Objective-C with foundation class NSException. @try − This block tries to execute a set of statements. @catch − This block tries to catch the exception in try block.

How do you throw an exception in Objective-C?

You throw (or raise) an exception by instantiating an NSException object and then doing one of two things with it: Using it as the argument of a @throw compiler directive. Sending it a raise message.


2 Answers

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;
}
like image 62
Casey Avatar answered Sep 21 '22 12:09

Casey


Not the answer I was hoping for, unfortunately:

Although Swift error handling resembles exception handling in Objective-C, it is entirely separate functionality. If an Objective-C method throws an exception during runtime, Swift triggers a runtime error. There is no way to recover from Objective-C exceptions directly in Swift. Any exception handling behavior must be implemented in Objective-C code used by Swift.

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

My next plan of attack is to add an Objective-C function I can call out to that will wrap the attempt in @try/@catch. This really sucks, Apple.

like image 43
devios1 Avatar answered Sep 24 '22 12:09

devios1