3

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];
2

1 Answer 1

5

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.

2
  • Any way to get around it using try catch blocks?
    – Amendale
    Aug 24, 2013 at 19:07
  • @user2303367 DDMathParser won't throw an exception, but it will also say that 3++2 is a valid expression (that evaluates to 5). Aug 24, 2013 at 22:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.