在Swift中捕捉NSException [英] Catching NSException in Swift

查看:246
本文介绍了在Swift中捕捉NSException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Swift中的以下代码引发NSInvalidArgumentException异常:

The following code in Swift raises NSInvalidArgumentException exception:

task = NSTask()
task.launchPath = "/SomeWrongPath"
task.launch()

如何捕获异常?据我了解,Swift中的try / catch是针对Swift中引发的错误,而不是针对NSTask之类的对象引发的NSExceptions(我猜是用ObjC编写的)。我是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...

编辑:这是该错误的雷达(特别是for 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

Don别忘了将此添加到您的 * -Bridging-Header.h:

Don't forget to add this to your "*-Bridging-Header.h":

#import "ObjC.h"

这篇关于在Swift中捕捉NSException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆