int main (int argc, const char * argv[]) { <br>
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
int a1,b1,c1;
@try {
NSLog(@"Enter numerator: ");
scanf("%i",&a1);
NSLog(@"Enter denomenator: ");
scanf("%i",&b1);
c1 = a1/b1;
NSLog(@"%i",c1);
}
@catch (NSException * e) {
NSLog([e name]);
NSLog([e description]);
NSLog([e reason]);
}
@finally {
NSLog(@"inside finally block");
}
[pool 开发者_如何学Cdrain];
return 0;
}
Here if i enter value of a1=10, b1=0, then there should be exception generated, so statement within catch block will supposed to be execute. But it doesn't. Program crashed. Try..Catch doesn't work in this case ......Looks like i am doing something wrong...
try/catch will only work for Obj-C exceptions that are thrown. They are quite high-level constructs. This is probably different from the Java try/catch blocks, that let you catch almost everything.
It looks like the OP just wants an example of try-catch-finally. Just in case anyone is else needs it, here's a basic example to work with ARC:
#import <Foundation/Foundation.h>
int main (int argc, char *argv[]) {
@autoreleasepool {
@try {
@throw ([NSException exceptionWithName:@"MyException"
reason:@"Just testing"
userInfo:nil]);
}
@catch (NSException *ex) {
NSLog(@"Exception caught: %@", ex);
}
@finally {
NSLog(@"Finally is executed whether there's an exception or not");
}
}
return 0;
}
You are seeing the floating point exception which is caused by C code (c1 = a1/b1). This is not wrapped in a NSException.
If you want to go through the catch block, you can replace your FPE code with
[[NSString string] setValue:@"" forKeyPath:@"KP"];
which will trigger a NSUnknownKeyException.
精彩评论