【问题标题】:Why use Try/Catch instead of testing for an NSError为什么使用 Try/Catch 而不是测试 NSError
【发布时间】:2012-10-08 17:03:54
【问题描述】:

有时你会看到一段 iOS - Objective-C 代码使用 Try/Catch 结构。

例如这个例子来自:http://docs.xrtml.org/2-1-0/pubsub/ios/ortcclient.html

- (void)viewDidLoad
{
    [super viewDidLoad];

    // Instantiate OrtcClient
    ortcClient = [OrtcClient OrtcClientWithConfig:self];

    // Post permissions
    @try {
        NSMutableDictionary* myPermissions = [[NSMutableDictionary alloc] init];

        [myPermissions setObject:@"w" forKey:@"channel1"];
        [myPermissions setObject:@"w" forKey:@"channel2"];
        [myPermissions setObject:@"r" forKey:@"channelread"];

        BOOL result = [ortcClient saveAuthentication:@"http://ortc-developers.realtime.co/server/2.1/" isCLuster:YES authenticationToken:@"myAuthenticationToken" authenticationTokenIsPrivate:NO applicationKey:@"myApplicationKey" timeToLive:1800 privateKey:@"myPrivateKey" permissions:myPermissions];

        if (result) {
            // Permissions correctly posted
        }
        else {
            // Unable to post permissions
        }
    }
    @catch (NSException* exception) {
        // Exception posting permissions
    }

    // Set connection properties
    [ortcClient setConnectionMetadata:@"clientConnMeta"];
    [ortcClient setClusterUrl:@"http://ortc-developers.realtime.co/server/2.1/"];

    // Connect
    [ortcClient connect:@"myApplicationKey" authenticationToken:@"myAuthenticationToken"];
}

为什么要使用这样的结构,难道你不能像'常规' Cocoa-Touch 代码那样检查来自saveAuthentication:isCLuster:authenticationToken:... 方法的NSError(间接)返回吗?例如读取 JSON 时:

NSError *error = nil;
id result = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error];

if (error == nil){
    NSLog(@"%@", result);
}else{
    NSLog(@"%@", [error localizedDescription]);
}

【问题讨论】:

  • 具有讽刺意味的是,如果给定的数据不是 JSON 可序列化的,NSJSONSerialization 实际上会引发异常。此外,错误不会被填充。

标签: objective-c cocoa-touch exception try-catch


【解决方案1】:

一般来说,try-catch 更健壮,不需要您定义测试位置的确切位置(可能是块)并提供有关异常的信息。

【讨论】:

    【解决方案2】:

    在您期望出现无法恢复或可能导致未定义行为(例如崩溃)的情况下使用 try catch,请使用NSError,其中 recovereable 错误是预期的,例如来自 json 对象或 xml 的错误值。

    你可以通过Apple documentation 了解异常编程。

    【讨论】:

    • 所以这段代码的创建者只是懒惰并且没有发现有必要测试所有内容,而是在它周围放置一个 Try/Catch?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-09-12
    • 2021-02-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多