Search code examples
objective-cinvalid-argumentnsexpression

NSExpression catch invalid arguments


I am using NSExpression to evaluate a mathematical string and it works great. However I want to have a way of catching an error when the input string is invalid, such as "3++2". Is there a way to go about doing this instead of the application terminating due to 'NSInvalidArgumentException'. Sorry, I am fairly new to objective-c. The code I am using now is:

NSExpression *exp = [NSExpression expressionWithFormat: string];
NSNumber *result = [exp expressionValueWithObject:nil context:nil];
answer = [result stringValue];

Solution

  • I think NSExpression is not the right tool for the job here. The class is part of the Cocoa predicate system and was designed to only accept well-formatted input.

    I suggest you look for a proper math parser. I believe GCMathParser is a good choice. There's also DDMathParser.

    If you insist on using NSExpression, you can catch the exception like this:

    @try {
      // the code that potentially raises an NSInvalidArgumentException
    } @catch (NSException *exception) {
      if ([[exception name] isEqualToString:NSInvalidArgumentException]) {
        // your error handling
      }
    }
    

    Be advised, however, that this is bad practice. Exceptions in Objective-C should only be used to catch unexpected runtime errors. Your example does not qualify.