0

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

prabodhprakash
  • 3,825
  • 24
  • 48

2 Answers2

3

[NSException new] instantiates a null class because it contains no useful information. It does not generate an NSException instance, and as such your:

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

is useless. However, if you use:

@catch (id exception)
{

}

You will catch this empty object.

An excerpt from the official documentation on Handling Exceptions:

You can have a sequence of @catch error-handling blocks. Each block handles an exception object of a different type. You should order this sequence of @catch blocks from the most-specific to the least-specific type of exception object (the least specific type being id) ...

Vatsal Manot
  • 17,695
  • 9
  • 44
  • 80
  • Thanks, that worked :) For everyone else, here is the link that discusses the same in more detail: https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/Exceptions/Tasks/HandlingExceptions.html#//apple_ref/doc/uid/20000059-SW1 – prabodhprakash May 20 '16 at 07:55
1

You'll have to initialize the NSException using the

@throw [NSException exceptionWithName:@"Exception!" reason:nil userInfo:nil];

or some other valid way to construct NSException listed in the "Creating and Raising an NSException Object" page in Apple documentation. https://developer.apple.com/library/ios/documentation/Cocoa/Reference/Foundation/Classes/NSException_Class/index.html#//apple_ref/occ/cl/NSException

Miro
  • 97
  • 3