Catch Objective-C exception in Swift

牧云@^-^@ 提交于 2019-12-09 09:40:18

问题


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.


回答1:


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



回答2:


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.




回答3:


I wanted to call out the answer given in this question:

Catching NSException in Swift

as you can still use the Swift do/catch with the call in a natural fashion, the next best thing to Swift actually catching ObjC exceptions as it should.



来源:https://stackoverflow.com/questions/35119531/catch-objective-c-exception-in-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!