4
votes

Excuses to my silly question, i wish to use a catch for specific exception, NSInvalidArgumentException, so, i have the next code in my OSX project:

@try

{

...

} @catch(NSInvalidArgumentException* exception )

{

...

}

but xcode say me: "unknown type name 'NSInvalidArgumentException'", so i i was importing

import "Foundation/Foundation.h" or

import "Foundation/NSException.h"

but nothing happen, somebody known in what package or library is NSInvalidArgumentException? or which is my error? or is strictly necessary catch all exception using the superclass NSException? in the developer documentation do not show that so be it.

best regards.

2
Jesus Christ, people: Objective-C is not Java. Fix your freaking exceptions, don't catch them. Exceptions are fatal, and should stay that way. That said, nobody in their right mind subclasses NSException. We throw exceptions with their type names as a parameter set at the creation of the exception. NSInvalidArgumenrException is a string constant somewhere.CodaFi
Man? i know that, but the reason for which the exception exist is because may happen, thank you for your comment :)Servio
@Rob and CodaFi thank you, now i know more about exception handling in objective-cServio

2 Answers

10
votes

NSInvalidArgumentException is not an exception type. It is a string that will be returned in the name property for an exception. So, you should catch your exception, and the name property does not match, you can re-@throw the exceptions you're not going to handle, e.g.:

@try {
    // code that generates exception
}
@catch (NSException *exception) {
    if ([exception.name isEqualToString:NSInvalidArgumentException])
    { 
        // handle it
    }
    else
    {
        @throw;
    }
}

See the Exception Programming Topics for more information.

I must confess that I share CodaFi's concern that this is not an appropriate use of exceptions. It's much better to program defensively, validate your parameters before you call Cocoa methods, and simply ensure that you don't generate exceptions in the first place. If you refer to the Dealing with Errors section of the Programming with Objective-C guide, exceptions are intended for "programmer errors" and they say:

You should not use a try-catch block in place of standard programming checks for Objective-C methods.

0
votes

somebody known in what package or library is NSInvalidArgumentException?

It is declared in the Foundation Framework, in NSException.h. As CodaFi wrote in the comment, it is not a type, it is a string constant, declared as FOUNDATION_EXPORT NSString * const NSInvalidArgumentException;

So importing more headers won't fix your problem, because @catch(NSInvalidArgumentException* exception ) is like writing @catch(@"A string constant"* exception ), you have an object, where a type is expected.

Having said that, don't use exceptions for flow control. Have a look at the last part of this answer on SO