prabodhprakash prabodhprakash - 6 months ago 19
Objective-C Question

@throw not caught by @catch block?

If there is a code which looks like

@try
{
@throw [NSException new];
}
@catch (NSException ex)
{
NSLog(@"exception caught");
}


in this case, the code does not go to @catch block, rather the application crashes. How should we catch exceptions throws by @throw in objective-c

Answer

[NSException new] instantiates a null class, essentially. It does not generate an NSException instance, and as such your:

@catch (NSException *ex)
{
    NSLog(@"exception caught");
}

is useless. However, if you add a:

@catch (id exception)
{

}

You'll see that your exception is caught. NSException is not meant to be instantiated like that, each instance is supposed to have a reason/code.

You should always have a least-specific error type case (id), especially when you are dealing with foreign APIs.