Reputation: 73
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.
Upvotes: 4
Views: 1543
Reputation: 438257
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.
Upvotes: 10
Reputation: 7720
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
Upvotes: 0