Reputation: 65409
Sometimes you see a piece of iOS - Objective-C code use a Try/Catch structure.
For example this example from: 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"];
}
Why use such a structure, couldn't you just check for an NSError (indirect) return from the saveAuthentication:isCLuster:authenticationToken:...
method like 'regular' Cocoa-Touch code does? For example when reading JSON:
NSError *error = nil;
id result = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error];
if (error == nil){
NSLog(@"%@", result);
}else{
NSLog(@"%@", [error localizedDescription]);
}
Upvotes: 1
Views: 509
Reputation: 1742
Use try catch where you expect a condition that cannot be recovered from or which may lead to an undefined behaviour such as crash, use NSError where recovereable errors are expected like wrong values from a json object or xml.
You can go throughApple documentation about exception programming.
Upvotes: 3
Reputation: 1251
In general, try-catch is more robust, does not require you to define an exact position of where to test (could be a block) and provides info about the exception.
Upvotes: 0