ArithmeticException은 자바(Java)에서 발생하는 런타임 예외(Runtime Exception) 중 하나로, 주로 산술 연산 중 오류가 발생할 때 던져집니다.
0으로 나누기 (Division by zero)
int a = 10;
int b = 0;
int result = a / b; // ArithmeticException: / by zero 발생
나머지 연산에서 0으로 나누기
int a = 10;
int b = 0;
int result = a % b; // ArithmeticException: / by zero 발생
Java의 BigInteger 클래스에서 잘못된 연산 수행
import java.math.BigInteger;
public class Main {
public static void main(String[] args) {
BigInteger big1 = new BigInteger("10");
BigInteger big2 = new BigInteger("0");
BigInteger result = big1.divide(big2); // ArithmeticException 발생
}
}
0으로 나누기 방지
if (b != 0) {
int result = a / b;
} else {
System.out.println("0으로 나눌 수 없습니다.");
}
예외 처리 (try-catch 블록 사용)
try {
int result = a / b;
} catch (ArithmeticException e) {
System.out.println("예외 발생: " + e.getMessage());
}
BigInteger 연산 시 조건 확인
if (!big2.equals(BigInteger.ZERO)) {
BigInteger result = big1.divide(big2);
} else {
System.out.println("0으로 나눌 수 없습니다.");
}
double 또는 float 타입에서는 0으로 나눠도 예외가 발생하지 않고 Infinity나 NaN이 반환됩니다.
double x = 10.0;
double y = 0.0;
System.out.println(x / y); // Infinity
정수 연산에서는 반드시 0으로 나누는 경우를 사전에 검사해야 합니다.