Access to objective-c exception in finally block

Given the following situation:

@try {
    @try {
        // raises an exception :)
        [receiver raisingFirstException];
    } @finally {
        // raises another exception :)
        [otherReceiver raisingFinalException];
    }
} @catch (id e) {
    printf("exception: %s\n", [[e stringValue] cString]);
}

Is there a way to get the first exception to @finallyblock or to get both exceptions in a block @catch?

I have some code where a block @finallyperforms some checks that may throw an exception, but I don't want to lose the original exception (the main reason).

If the original exception was not, but the checks are not performed, I want the exception that they throw.

+3
source share
1 answer

The best way to do this is to assign an exception to a variable accessible from the rest of your block.

NSException *ex;
@try {
    @try {
        [someObject methodWhichCouldThrowException];
    } @catch (NSException *e) {
        ex = e;
    } @finally {
        [anotherObject methodWhichCouldThrowADifferentException];
    }
} @catch (NSException *e) {
    // From here you can access both the exception thrown by 'someObject'
    // as well as the exception thrown by 'anotherObject'.
}
+2
source

Source: https://habr.com/ru/post/1706925/


All Articles