I can't seem to get a division by zero exception to be trapped by a simple try/catch block. I tried the following code:
@try {
accumulator /= value;
}
@catch ( NSException* exception ) {
NSLog( @"Caught %@: %@", [exception name], [exception reason] );
}
Which didn't do much (the division by zero produced -inf, but no exception was raised).
So I changed the program to use integers instead of floating point numbers, after which the program would exit prematurely with the message "Floating point exception." Which is odd for two reasons: 1) it is all integer math now, so why a floating point exception and 2) why wasn't the exception propagated up from the system into the Objective-C try/catch block?
Ultimately, I read the Xcode documentation section on throwing exceptions and found an example of how to throw one, so I solved the Exercise as follows (which works for both floating point and integer math):
@try {
if ( value == 0 ) {
NSException *e = [NSException exceptionWithName: @"Floating point exception"
reason: @"Division by zero" userInfo: nil];
@throw e;
}
accumulator /= value;
}
@catch ( NSException* exception ) {
NSLog( @"Caught %@: %@", [exception name], [exception reason] );
}
Perhaps I've missed something and this is indeed the intended solution for the exercise?
If not, is there something I'm doing wrong? It sure seems a lot more convenient to write the simpler try/catch and count on the system exception climbing up the exception chain instead of using the manual check in my solution.