有时,您会看到一段使用Try/Catch结构的iOS - Objective-C代码。
例如,以下示例来自: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]);
}发布于 2012-10-18 17:31:29
在你期望无法恢复或者可能导致未定义的行为的地方使用try catch,比如crash,在可恢复的错误被期望的地方使用NSError,就像来自json对象或xml的错误值一样。
你可以通过Apple documentation 了解异常编程。
发布于 2012-10-18 17:30:27
通常,try-catch更健壮,不需要您定义测试位置的确切位置(可以是一个块),并提供有关异常的信息。
https://stackoverflow.com/questions/12951260
复制相似问题