try/catch/throw/finally example?

Sunday, August 27 2006 @ 09:30 AM BST

Contributed by: Admin

Can someone provide an example of the use of @try, @catch, @throw, @finally, in Objective-C ?


#import 

int main(int argc, char **argv)
{
	NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init] ;
	
	int result = 0	;
	
	@try {
	   if (argc > 1)	{
		@throw [NSException exceptionWithName:@"Throwing a test exception" reason:@"Testing the @throw directive." userInfo:nil];
	   }
	} 
	@catch (id theException) {
		NSLog(@"%@", theException);
		result = 1	;
	} 
	@finally {
		NSLog(@"This always happens.");
		result += 2	;
	}
	
	NSLog(@"Leaving ...");
	[pool release]	;
	return result	;
}
Compile with:

cc -framework Foundation -fobjc-exceptions test.m
Test it with:

./a.out ; echo $?
will result in:

a.out[6108] This always happens.
a.out[6108] Leaving ...
2
and

./a.out 1 ; echo $?
will result in:

a.out[6107] Testing the @throw directive.
a.out[6107] This always happens.
a.out[6107] Leaving ...
3

0 comments



http://www.macosxguru.net/article.php?story=20060827093013582