Pages

Sunday, December 27, 2009

Objective-C. Exception Handling Using @try

For me it is a bit strange that Xcode compiles this code:
#import <Foundation/Foundation.h>

@interface Test: NSObject
{
int x;
}

@property int x;
-(void) print;

@end

@implementation Test

@synthesize x;

-(void) print
{
NSLog(@"x = %i", x);
}

@end


int main (int argc, const char * argv[]) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

Test* test = [[Test alloc] init];
test.x = 10;
[test print];

[test noSuchMethod];

[test release];
[pool drain];
return 0;
}
As you see I call noSuchMethod from the test object. Xcode shows just a warning:


Of course, the application crashes:


The book recommends to use @try in such cases:
@try {
[test noSuchMethod];
}
@catch (NSException *exception) {
NSLog(@"Caught %@%@", [exception name], [exception reason]);
}

And so here is the console:


@finally block also can be used and works exactly as in any C++ compiler. Same is right about @throw directive.

No comments:

Post a Comment