开发者

Objective-C Exception Handling: "Divided by Zero Exception" is not getting caught

I have the following code in my program.

@try {

    float result =  4 / 0; // LINE 1

} @catch (NSException *e) {

    NSLog(@"Exception : %@", e);
    return 0;
}

I expected an exception to be caught in LINE 1 and thrown to the @catch block. But the execution aborts at LINE 1 showing EXC_ARITHMETIC in console.

What am I doing wrong here? What necessary things I have to do to do ex开发者_如何学Goception handling?


EXC_ARITHMETIC is a type of low-level exception known as a "signal". The only way to catch them is to register a signal handler, for example:

#include<signal.h>
void handler(int signal) {
    if (signal == FPE_FLTDIV)
        printf("Divide by 0 exception\n");
}

signal(SIGFPE, handler);    

However, the only safe thing to do in such a handler is clean up any resources and exit cleanly.


Divide by zero is not an NSException.

Give this a try (I never tried though):

@try {

    float result =  4 / 0; // LINE 1

} @catch (NSException *e) {

    NSLog(@"Exception : %@", e);
    return 0;
}
@catch (id ue) {

    //DIVIDE BY ZERO ATTEMPT MAY ENDUP HERE
    NSLog(@"Exception : %@", ue);
    return 0;
}

====== EDIT =======

Turns out divide by zero is not a obj-c exception. But seems you can catch such exceptions globally.

How do I catch global exceptions?


Exceptions List and division by zero isn't a predefined exception. Also, to know the type of exception, you should send name message to the exception object.

NSLog(@"Exception : %@", [ e name ] );


Actually float result = 4 / 0; would never raise any kind of signal or exception (xcode, LLVM). No idea why it just silently returns inf into result.


"4 / 0" is an expression with known literals, which can be very easily computed by compile time -- therefore there will be no runtime exception on that...


I am using the LLVM 5.1 compiler. In a *.m file just tried the line

float result = 4 / 0;

and

int result = 4 / 0;

and both give the result to be zero. But, because both contain the expression 4 / 0 which is integer division by zero regardless of the variable definition type, the compiler only gives a warning. All other compilers that I have used would have given an error from this expression.

The C language only specifies that integer division by zero is undefined. The compilers used in this case apparently define the result to be zero. This is a good example of why you should never depend on undefined behavior behaving the way you expect.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜