Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ObjC: Error handling... what to return

Apologies for such a newbie question.

I have written a class method that takes three strings and returns a substring.

I have written conditional statements that only allow the substring to returned if certain criteria are met. However I am unsure what I need to return if the substring cannot be extracted. At the moment I have the method returning a default 'error' string, but I have the feeling that this may not be best practice.

Here is my method:

+(NSString *)ExtractSubstringFrom:(NSString *)sourceString 
             Between:(NSString *)firstString And:(NSString *)secondString {


             NSRange stringRangeOne = [sourceString rangeOfString:secondString];
             NSString *resultString;

             if (stringRangeOne.location != NSNotFound) {
             resultString = [sourceString substringToIndex:stringRangeOne.location]; 
             }

             NSRange stringRangeTwo = [sourceString rangeOfString:firstString];

             if (stringRangeTwo.location !=NSNotFound) {
             resultString = [resultString substringFromIndex:stringRangeTwo.location+stringRangeTwo.length];
             return resultString; 
             }

             else return @"Error!";

             //To do... improve error checking

             }

How can I make this method more error friendly?

like image 429
Oliver Avatar asked Mar 24 '13 21:03

Oliver


1 Answers

There are several ways of handling errors of this kind in Objective C:

  • Returning the default value - typically, the default value is nil. Since performing operations on nil objects is allowed in Objective C, this is relatively safe.
  • Producing NSError objects - this is more typical of errors that can be addressed by end users, such as connection and configuration problems. The unfortunate side effect of this kind of API is the need to set up and pass an extra parameter.
  • Using an assertion - this is a good way of handling "programming errors", i.e. when your program's arguments are out of their specified ranges.
  • Throwing an exception - this option is available in the language, but Apple strongly discourages against using it. I mentioned it here for completeness, even though I never use this option myself.
like image 64
Sergey Kalinichenko Avatar answered Oct 01 '22 21:10

Sergey Kalinichenko