user65544 user65544 - 6 months ago 7
Java Question

How to handle divide by 0

if (getOperator=="/"){
try {
sum = value1/value2;
} catch (Exception e) {
summaryTxt.setText("Invalid operation");
}
}


What's wrong here?

Answer

It is wrong, and this is a bad practise.

Imagine, that value1 can be Integer and it is null. Then you will catch a NullPointerException, but your code will tell you that the operation is invalid, but it is not.

Exceptions are not for checking conditions. Better to check them explicitly:

     if (getOperator=="/"){
        if (value2 == 0) {
           summaryTxt.setText("Value2 can't be 0!");
        } else {
           sum = value1/value2;
        }
      }
Comments