在Swift中捕获NSException

前端之家收集整理的这篇文章主要介绍了在Swift中捕获NSException前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
下面的代码在Swift中引发NSInvalidArgumentException异常:
task = NSTask()
task.launchPath = "/SomeWrongPath"
task.launch()

如何捕获异常?据我所知,在Swift中的try / catch是针对在Swift中抛出的错误,而不是针对从NSTask(我猜是用ObjC写的)等对象引发的NSExceptions。我是新来的Swift,所以可能是我缺少明显的东西…

编辑:这里是一个雷达的Bug(专门为NSTask):openradar.appspot.com/22837476

这里是一些代码,将NSExceptions转换为Swift 2错误

现在你可以使用

do {
    try ObjC.catchException {

       /* calls that might throw an NSException */
    }
}
catch let error {
    print("An error ocurred: \(error)")
}

ObjC.h:

#import <Foundation/Foundation.h>

@interface ObjC : NSObject

+ (BOOL)catchException:(void(^)())tryBlock error:(__autoreleasing NSError **)error;

@end

ObjC.m

#import "ObjC.h"

@implementation ObjC 

+ (BOOL)catchException:(void(^)())tryBlock error:(__autoreleasing NSError **)error {
    @try {
        tryBlock();
        return YES;
    }
    @catch (NSException *exception) {
        *error = [[NSError alloc] initWithDomain:exception.name code:0 userInfo:exception.userInfo];
    }
}

@end

不要忘记将它添加到您的“* -Bridging-Header.h”:

#import "ObjC.h"
原文链接:https://www.f2er.com/swift/320761.html

猜你在找的Swift相关文章