Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Specific exception in objective-c

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.

like image 486
Servio Avatar asked Dec 26 '22 23:12

Servio


1 Answers

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.

like image 150
Rob Avatar answered Jan 14 '23 04:01

Rob