Re: try/catch/throw/finally example?
Re: try/catch/throw/finally example?
- Subject: Re: try/catch/throw/finally example?
- From: Cameron Hayne <email@hidden>
- Date: Sat, 26 Aug 2006 05:03:00 -0400
On 26-Aug-06, at 3:02 AM, Gerriet M. Denkmann wrote:
what is the @finally clause good for, as the next statement after
the @try block also gets executed in all cases?
Or what am I missing?
You are missing the fact that the 'finally' clause gets executed even
if there is a 'return' (or other control-flow statement) in the 'try'
or 'catch' clauses.
Look at the following code and note especially the 'return' statement
in the 'catch' clause.
-------------------------------------
#import <Foundation/Foundation.h>
void doSomething()
{
NSLog(@"Start of function");
NSString *stringOne = @"One";
NSString *stringTwo = @"Two";
@try
{
[stringOne appendString:stringTwo];
}
@catch (id theException)
{
NSLog(@"%@ doesn't respond to appendString:!", [stringOne
class]);
return; // Note that the return is delayed until after the
'finally'
}
@finally
{
NSLog(@"This always happens");
}
NSLog(@"End of function"); // this won't get executed since
there is a 'return' in the 'catch' clause
}
int main ()
{
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
doSomething();
[pool release];
return 0;
}
-------------------------------------
% gcc -fobjc-exceptions -framework Foundation -o exceptions exceptions.m
exceptions.m: In function 'doSomething':
exceptions.m:12: warning: 'NSString' may not respond to '-appendString:'
exceptions.m:12: warning: (Messages without a matching method signature
exceptions.m:12: warning: will be assumed to return 'id' and accept
exceptions.m:12: warning: '...' as arguments.)
% ./exceptions
2006-08-26 04:56:34.623 exceptions[15994] Start of function
2006-08-26 04:56:34.627 exceptions[15994] *** -[NSConstantString
appendString:]: selector not recognized [self = 0x500c]
2006-08-26 04:56:34.628 exceptions[15994] NSConstantString doesn't
respond to appendString:!
2006-08-26 04:56:34.629 exceptions[15994] This always happens
--
Cameron Hayne
email@hidden
_______________________________________________
Do not post admin requests to the list. They will be ignored.
Cocoa-dev mailing list (email@hidden)
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden