Contribute  :  Calendar  :  Advanced Search  :  Site Statistics  :  Directory  :  Files to download  :  Links for developers  :  Privacy policy  :  Web Resources  :  Polls  
    MacOSX Guru Site Information, tips and tricks, FAQ for Mac OS X developers    
 Welcome to MacOSX Guru Site
 Thursday, April 27 2017 @ 05:51 PM BST

try/catch/throw/finally example?

   
Cocoa Development FAQCan 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
 

What's Related

Story Options

try/catch/throw/finally example? | 0 comments | Create New Account
The following comments are owned by whomever posted them. This site is not responsible for what they say.
 Copyright © 2017 MacOSX Guru Site
 All trademarks and copyrights on this page are owned by their respective owners.
Powered By Geeklog 
Created this page in 0.06 seconds