Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error/Exception handling in a method that returns bool

In my custom framework, I have a method like the one shown below which fetches value from dictionary and converts it into BOOL and returns the boolean value.

- (BOOL)getBoolValueForKey:(NSString *)key;

What if the caller of this method passes a key that does not exist. Should I throw a custom NSException saying key does not exist(but throwing exception is not recommended in objective c) or add NSError parameter to this method as shown below?

- (BOOL)getBoolValueForKey:(NSString *)key error:(NSError **)error; 

If I use NSError, I will have to return 'NO' which will be misleading since 'NO' can be a valid value of any valid key.

like image 275
saikamesh Avatar asked Oct 18 '16 15:10

saikamesh


People also ask

What is exception handling in spring Bool RESTful?

When you develop a Spring Bool RESTful service, you as a programmer are responsible for handling exceptions in the service. For instance, by properly handling exceptions, you can stop the disruption of the normal flow of the application. In addition, proper exception handling ensures that the code doesn’t break when an exception occurs.

Should I throw exceptions or booleans?

The answer is it depends, or both. If you are the user of that method, and know this is an infrequent occurrence, throw exceptions. If you are user of the method, and know it is a frequent error, use booleans. If you don't know the frequence because you are not the only user, have a Try pattern.

How do I handle an exception in an exception handler?

Ordinarily, an exception handler that catches an AggregateException exception uses a foreach loop (in C#) or For Each loop (in Visual Basic) to handle each exception in its InnerExceptions collection. Instead, the following example uses the Handle method to handle each exception, and only rethrows exceptions that are not CustomException instances.

What happens if an argument exception is not handled?

// // ArgumentException: The path is not of a legal form. Each invocation of the predicate returns true or false to indicate whether the Exception was handled. After all invocations, if any exceptions went unhandled, all unhandled exceptions will be put into a new AggregateException which will be thrown. Otherwise, the Handle method simply returns.


Video Answer


2 Answers

The API for this is long-established by NSUserDefaults, and should be your starting point for designing your API:

- (BOOL)boolForKey:(NSString *)defaultName;

If a boolean value is associated with defaultName in the user defaults, that value is returned. Otherwise, NO is returned.

You should avoid creating a different API for fetching bools from a keystore unless you have a strong reason. In most ObjC interfaces, fetching a non-exixtant key returns nil and nil is interpreted as NO in a boolean context.

Traditionally, if one wants to distinguish between NO and nil, then call objectForKey to retrieve the NSNumber and check for nil. Again, this is behavior for many Cocoa key stores and shouldn't be changed lightly.

However, it is possible that there is a strong reason to violate this expected pattern (in which case you should definitely note it carefully in the docs, because it is surprising). In that case, there are several well established patterns.

First, you can consider fetching an unknown key to be a programming error and you should throw an exception with the expectation that the program will soon crash because of this. It is very unusual (and unexpected) to create new kinds of exceptions for this. You should raise NSInvalidArgumentException which exists exactly for this problem.

Second, you can distinguish between nil and NO by correctly using a get method. Your method begins with get, but it shouldn't. get means "returns by reference" in Cocoa, and you can use it that way. Something like this:

- (BOOL)getBool:(BOOL *)value forKey:(NSString *)key {
    id result = self.values[key];
    if (result) {
        if (value) {
            // NOTE: This throws an exception if result exists, but does not respond to 
            // boolValue. That's intentional, but you could also check for that and return 
            // NO in that case instead.
            *value = [result boolValue]; 
        }
        return YES;
    }

    return NO;
}

This takes a pointer to a bool and fills it in if the value is available, and returns YES. If the value is not available, then it returns NO.

There is no reason to involve NSError. That adds complexity without providing any value here. Even if you are considering Swift bridging, I wouldn't use NSError here to get throws. Instead, you should write a simple Swift wrapper around this method that returns Bool?. That's a much more powerful approach and simpler to use on the Swift side.

like image 80
Rob Napier Avatar answered Oct 17 '22 17:10

Rob Napier


If you wish to communicate passing a non-existent key as a programmer error, i.e. something that should actually never occur during runtime because for instance something upstream should have taken care of that possibility, then an assertion failure or NSException is the way to do it. Quoting Apple's documentation from the Exception Programming Guide:

You should reserve the use of exceptions for programming or unexpected runtime errors such as out-of-bounds collection access, attempts to mutate immutable objects, sending an invalid message, and losing the connection to the window server. You usually take care of these sorts of errors with exceptions when an application is being created rather than at runtime.

If you wish to communicate a runtime error from which the program can recover / can continue executing, then adding an error pointer is the way to do it.

In principle it is fine to use BOOL as the return type there even if there is a non-critical error case. There are however corner cases with this in case you intend to interface with this code from Swift:

  • If you are accessing this API via Swift, NO always implies that an error is thrown, even if in your Objective-C method implementation you do did not populate the error pointer, i.e. you would need a do / catch and handle specifically of a nil error.
  • The opposite actually is also valid, i.e. it is possible to throw an error in the success case (NSXMLDocument for instance does this to communicate non-critical validation errors). There is to my knowledge no way to communicate this non-critical error information to Swift.

If you do intend to use this API from Swift, I would perhaps box the BOOL to a nullable NSNumber (at which case the error case would be nil, and the successful NO case would be an NSNumber with NO wrapped in it).

I should note, for the specific case of a potentially failable setter, there are strong conventions that you should follow, as noted in one of the other answers.

like image 34
mz2 Avatar answered Oct 17 '22 15:10

mz2