Catching exceptions with objective-c in Linux
I have some sample code that doesn't run the way I think it should.
#import <Foundation/NSString.h>
#import <Foundation/NSException.h>
#import <Foundation/NSAutoreleasePool.h>
#import <std开发者_StackOverflow中文版io.h>
int main( int argc, const char *argv[] ) {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
@try {
NSException *e = [NSException
exceptionWithName: @"NSException"
reason: @"The level is below 0"
userInfo: nil];
@throw e;
} @catch ( NSException *e ) {
printf( "+%s: ", [[e name] UTF8String] );
}
[pool release];
}
I run it as following:
> gcc -g -c main.m -fconstant-string-class=NSConstantString -I/usr/include/GNUstep
> gcc main.o -lgnustep-base
> ./a.out
The result is:
Aborted
A little bit of playing with the GNU debugger showed me that the catch clause is never reached. It seems to work mac though.
Why do I not get into the catch clause?
The answers needed can be found in this mail thread: http://www.mail-archive.com/discuss-gnustep@gnu.org/msg11979.html
To get proper objective-c exception handling one might need to compile with the -fobjc-exceptions flag.
> gcc -g -c main.m -fconstant-string-class=NSConstantString -fobjc-exceptions -I/usr/include/GNUstep
> gcc main.o -lgnustep-base
> ./a.out
精彩评论