Hi all, I have written the following code for the java exercise “Calculator Conundrum”:
class CalculatorConundrum {
public String calculate(int operand1, int operand2, String operation) {
try {
if (operation == "+") {
return Integer.toString(operand1) + " + " + Integer.toString(operand2) + " = " + Integer.toString(operand1 + operand2);
} else if (operation == "*") {
return Integer.toString(operand1) + " * " + Integer.toString(operand2) + " = " + Integer.toString(operand1 * operand2);
} else if (operation == "/" && operand2 != 0) {
return Integer.toString(operand1) + " / " + Integer.toString(operand2) + " = " + Integer.toString(operand1 / operand2);
} else {
if (operation == null) {
throw new IllegalArgumentException("Operation cannot be null");
} else if (operation == "") {
throw new IllegalArgumentException("Operation cannot be empty");
} else if (operation != "+" && operation != "*" && operation != "/") {
throw new IllegalOperationException("Operation \'" + operation + "\' does not exist");
}
}
return Integer.toString(operand1 + operand2);
} catch (ArithmeticException e) {
System.out.println("Catching arithmetic exception");
throw new IllegalOperationException("Division by zero is not allowed", e);
}
}
}
However, my division by zero test case is failing with the following message:
Message:
Expecting code to raise a throwable.
Exception: java.lang.AssertionError:
Expecting code to raise a throwable.
at CalculatorConundrumTest.throwExceptionForDivisionByZero(CalculatorConundrumTest.java:85)
at java.base/java.lang.reflect.Method.invoke(Method.java:580)
at java.base/java.util.ArrayList.forEach(ArrayList.java:1596)
at java.base/java.util.ArrayList.forEach(ArrayList.java:1596)
Why does it not consider my exception block code as a valid way to handle this case?