Throw a runtime error on division by zero

This commit is contained in:
Tom Willemse 2020-11-11 22:01:10 -08:00
parent 5ff2f8be5a
commit 0068365533

View file

@ -119,9 +119,14 @@ class Interpreter implements Expr.Visitor<Object> {
} }
throw new RuntimeError(expr.operator, "Operands must be two numbers or two strings."); throw new RuntimeError(expr.operator, "Operands must be two numbers or two strings.");
case SLASH: case SLASH: {
checkNumberOperands(expr.operator, left, right); checkNumberOperands(expr.operator, left, right);
return (double) left / (double) right; double rhs = (double) right;
if (rhs == 0) {
throw new RuntimeError(expr.operator, "Division by zero.");
}
return (double) left / rhs;
}
case STAR: case STAR:
checkNumberOperands(expr.operator, left, right); checkNumberOperands(expr.operator, left, right);
return (double) left * (double) right; return (double) left * (double) right;