java как корректно вкинуть ArithmeticExeption при делении на 0
подскажите, как дооформить таск, чтобы отрабатывал проброс ошибок и return в случае корректного вычисления (b!=0)? Если я понимаю правильно, то при делении положительного на 0 должно быть Infinity, отрицательного -Infinity, 0 на 0 -- NaN. но при попытке округлить Infinity округляется.
public class test {
public static int precision = 3;
public static double a = -2.34567;
public static double b = 0;
public static double div(double a, double b, int precision) throws IOException {
try {
double res = a / b;
double resRound = Math.round(res * Math.pow(10, precision)) / Math.pow(10, precision);
} catch (ArithmeticException e) {
System.out.println("ArithmeticException");
}
}}
Ответы (2 шт):
Автор решения: Arty Morris
→ Ссылка
try {
double res = a / b;
double resRound = Math.round(res * Math.pow(10, precision)) / Math.pow(10, precision);
} catch (ArithmeticException e) {
res=0; //здесь можно что-то другое
System.out.println("ArithmeticException");
}
return res;
Автор решения: Alexander Pavlov
→ Ссылка
double res = a / b;
if (Double.isNaN(res) || Double.isInfinite(res)) {
throw new ArithmeticException("...");
}
return Math.round(res * Math.pow(10, precision)) / Math.pow(10, precision);