NSExpression catch invalid arguments

久未见 提交于 2019-12-04 13:45:07

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!