From 006836553321d5ce25ff4de4b5a71f19606fec37 Mon Sep 17 00:00:00 2001 From: Tom Willemse Date: Wed, 11 Nov 2020 22:01:10 -0800 Subject: [PATCH] Throw a runtime error on division by zero --- src/com/craftinginterpreters/lox/Interpreter.java | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/src/com/craftinginterpreters/lox/Interpreter.java b/src/com/craftinginterpreters/lox/Interpreter.java index 57e697c..1d87b87 100644 --- a/src/com/craftinginterpreters/lox/Interpreter.java +++ b/src/com/craftinginterpreters/lox/Interpreter.java @@ -119,9 +119,14 @@ class Interpreter implements Expr.Visitor { } throw new RuntimeError(expr.operator, "Operands must be two numbers or two strings."); - case SLASH: + case SLASH: { 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: checkNumberOperands(expr.operator, left, right); return (double) left * (double) right;