Skip to content
Dave DeLong edited this page Sep 18, 2015 · 1 revision

It is very important that you implement error handling while using DDMathParser, especially if the strings you are interpreting are supplied by the user.

Error handling is accomplish via the standard Swift error handling mechanism, which means your evaluations will always need to be surrounded by do { ... } catch { } blocks.

Several different kinds of errors may be thrown depending on what the error actually is. All errors (with the exception of evaluation errors) include a range property that indicate where (in the original string) the error was encountered. This range is useful for providing feedback to the user on where they need to correct their input.

Tokenization Errors

These errors arise during the initial phase of parsing, and include things like:

  • empty variables (a $ followed by nothing, or an empty set of quotes)
  • coming across something that looks like an operator but isn't in the set of allowed operators

For a full list of the kinds of TokenizerErrors that may be reported, please refer to RawToken.swift.

Resolution Errors

Resolution errors occur when trying to figure out what the individual tokens actually mean. There are four kinds of resolution errors:

  1. Failing to parse a hexadecimal number
  2. Failing to parse a localized number
  3. Unable to recognize an operator
  4. Unable to disambiguate an operator

In general, resolution errors are relatively rare.

Grouping Errors

There are four kinds of grouping errors:

  1. Missing an open parenthesis. Example: "3 + 4)"
  2. Missing a close parenthesis. Example: "(3 + 4"
  3. Passing an empty argument to a function. Example: "add(1,)"
  4. An empty group. Example: "1 + ()"

Expression Errors

Expression errors occur during the final phase of parsing, when the intermediate representations are turned into the final Expression object. The errors that may be thrown from here are:

  1. A syntactically incorrect string, such as "1 2"
  2. An operator that is missing its left operand, such as "/ 3"
  3. An operator that is missing its right operand, such as "1 /"

Evaluation Errors

Evaluation errors occur when an Expression is evaluated by an Evaluator. For example, trying to divide by zero will throw an error, as will trying to evaluate a string with an unknown function or an unknown variable.