-
Notifications
You must be signed in to change notification settings - Fork 153
Errors
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.
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 occur when trying to figure out what the individual tokens actually mean. There are four kinds of resolution errors:
- Failing to parse a hexadecimal number
- Failing to parse a localized number
- Unable to recognize an operator
- Unable to disambiguate an operator
In general, resolution errors are relatively rare.
There are four kinds of grouping errors:
- Missing an open parenthesis. Example:
"3 + 4)"
- Missing a close parenthesis. Example:
"(3 + 4"
- Passing an empty argument to a function. Example:
"add(1,)"
- An empty group. Example:
"1 + ()"
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:
- A syntactically incorrect string, such as
"1 2"
- An operator that is missing its left operand, such as
"/ 3"
- An operator that is missing its right operand, such as
"1 /"
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.