在 Swift 中捕获 NSException [英] Catching NSException in Swift
问题描述
Swift 中的以下代码引发 NSInvalidArgumentException 异常:
The following code in Swift raises NSInvalidArgumentException exception:
task = NSTask()
task.launchPath = "/SomeWrongPath"
task.launch()
如何捕捉异常?据我了解,Swift 中的 try/catch 是针对 Swift 中引发的错误,而不是针对从 NSTask(我猜是用 ObjC 编写的)之类的对象引发的 NSExceptions.我是 Swift 的新手,所以可能我遗漏了一些明显的东西......
How can I catch the exception? As I understand, try/catch in Swift is for errors thrown within Swift, not for NSExceptions raised from objects like NSTask (which I guess is written in ObjC). I'm new to Swift so may be I'm missing something obvious...
编辑:这里是错误的雷达(特别是 NSTask):openradar.appspot.com/22837476
Edit: here's a radar for the bug (specifically for NSTask): openradar.appspot.com/22837476
推荐答案
这里有一些代码,将 NSExceptions 转换为 Swift 2 错误.
Here is some code, that converts NSExceptions to Swift 2 errors.
现在你可以使用
do {
try ObjC.catchException {
/* calls that might throw an NSException */
}
}
catch {
print("An error ocurred: (error)")
}
ObjC.h:
#import <Foundation/Foundation.h>
@interface ObjC : NSObject
+ (BOOL)catchException:(void(^)(void))tryBlock error:(__autoreleasing NSError **)error;
@end
ObjC.m
#import "ObjC.h"
@implementation ObjC
+ (BOOL)catchException:(void(^)(void))tryBlock error:(__autoreleasing NSError **)error {
@try {
tryBlock();
return YES;
}
@catch (NSException *exception) {
*error = [[NSError alloc] initWithDomain:exception.name code:0 userInfo:exception.userInfo];
return NO;
}
}
@end
不要忘记将其添加到您的*-Bridging-Header.h"中:
Don't forget to add this to your "*-Bridging-Header.h":
#import "ObjC.h"
这篇关于在 Swift 中捕获 NSException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!