Specific exception in objective-c

Sorry for my stupid question, I want to use catch for a specific exception, NSInvalidArgumentException, so I have the following code in my OSX project:

@try

{

...

} @catch (NSInvalidArgumentException * exception)

{

...

}

but xcode tell me: "unknown type name" NSInvalidArgumentException ", so I imported

import "Foundation / Foundation.h" or

import "Foundation / NSException.h"

but nothing happens, does anyone know which package or library has an NSInvalidArgumentException? or is it my mistake? or is it strictly necessary to catch all exceptions using the NSException superclass? the developer documentation does not show that it is so.

Regards.

+4
source share
2 answers

NSInvalidArgumentException not an exception type. This is the string that will be returned in the name property for an exception. Thus, you must catch your exception, and the name property does not match, you can return @throw exceptions that you are not going to handle, for example:

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

For more information, see Exception Programming Topics .

I must admit that I share the concern of CodaFi that this is the misuse of exceptions. It's much better to program protection, check your parameters before you call Cocoa methods, and just make sure you don't throw exceptions in the first place. If you refer to the Working with Errors section of the Program using the Objective-C manual, the exceptions are for "programmer errors," and they say:

You should not use the try-catch block instead of the standard programming checks for Objective-C methods.

+8
source

Does anyone know which package or library has an NSInvalidArgumentException?

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

So importing more headers will not fix your problem, because @catch(NSInvalidArgumentException* exception ) is like @catch(@"A string constant"* exception ) , you have an object where the type is expected.

Having said that, do not use exceptions to control the flow. Take a look at the last part of this answer on SO

0
source

Source: https://habr.com/ru/post/1495634/


All Articles