Skip to content

Instantly share code, notes, and snippets.

@zhihuitang
Last active June 10, 2019 04:06
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zhihuitang/6d3de0963d96a552d47721a598ca79c8 to your computer and use it in GitHub Desktop.
Save zhihuitang/6d3de0963d96a552d47721a598ca79c8 to your computer and use it in GitHub Desktop.
How to properly catch NSExceptions in Swift?
//
// OCCatch.h
//
//
#ifndef OCCatch_h
#define OCCatch_h
// add the code below to your -Bridging-Header.h
/**
#import "OCCatch.h"
*/
// How to use it in Swift?
/**
let exception = tryBlock {
let statusBar = UIApplication.shared.value(forKey: "statusBar") as? UIView
//......
}
if let exception = exception {
print("exception: \(exception)")
}
*/
#import <Foundation/Foundation.h>
NS_INLINE NSException * _Nullable tryBlock(void(^_Nonnull tryBlock)(void)) {
@try {
tryBlock();
}
@catch (NSException *exception) {
return exception;
}
return nil;
}
#endif /* OCCatch_h */
@sukh1993
Copy link

sukh1993 commented Aug 2, 2018

hello sir ,
can u explain me why we use this bridge file

@zhihuitang
Copy link
Author

zhihuitang commented Aug 3, 2018

Hi @sukh1993,

The reason is that in Swift project, sometimes the crash happens in the Objective-C side, we cannot use try { } catch { } to catch Objective-C crash. In that case we have to use a Objective-C wrapper to catch it.
For example: https://stackoverflow.com/questions/44167577/using-private-api-to-read-wifi-rssi-value/48083845?noredirect=1#comment88290822_48083845

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment