java.lang.ArithmeticException은 Java에서 발생하는 대표적인 비검사 예외(unchecked exception)입니다. 비검사 예외란 RuntimeException을 상속하는 예외로, 컴파일러가 반드시 처리하도록 강제하지 않는 예외를 의미합니다. 가장 흔하게 접하는 사례는 java.lang.ArithmeticException: / by zero로, 두 수를 나누려 할 때 분모가 0이면 발생합니다. ArithmeticException 객체는 JVM에 의해 생성될 수 있습니다.
예제 1
public class ArithmeticExceptionTest {
public static void main(String[] args) {
int a = 0, b = 10;
int c = b/a;
System.out.println("Value of c is : "+ c);
}
}위 예제에서는 변수 a의 값이 0, 즉 분모가 0이기 때문에 ArithmeticException이 발생합니다.
- java.lang.ArithmeticException: Java가 나눗셈 연산 도중 던지는 예외 클래스입니다.
- / by zero: ArithmeticException 객체를 생성할 때 함께 전달되는 상세 메시지(detail message)입니다.
실행 결과
Exception in thread "main" java.lang.ArithmeticException: / by zero
at ArithmeticExceptionTest.main(ArithmeticExceptionTest.java:5)ArithmeticException 처리 방법
try와 catch 블록을 사용하여 ArithmeticException을 처리해 보겠습니다.
- ArithmeticException을 발생시킬 가능성이 있는 문장들을 try와 catch 블록으로 감쌉니다.
- catch 블록에서 ArithmeticException을 잡아(catch)냅니다.
- 프로그램 실행이 중단(abort)되지 않으므로, 필요한 후속 조치를 취하고 정상적으로 계속 진행할 수 있습니다.
예제 2
public class ArithmeticExceptionTest {
public static void main(String[] args) {
int a = 0, b = 10 ;
int c = 0;
try {
c = b/a;
} catch (ArithmeticException e) {
e.printStackTrace();
System.out.println("We are just printing the stack trace.\n"+ "ArithmeticException is handled. But take care of the variable \"c\"");
}
System.out.println("Value of c :"+ c);
}
}예외가 발생하면 실행 흐름은 예외가 발생한 지점에서 곧바로 catch 블록으로 이동합니다. catch 블록 안의 문장들이 모두 실행된 후에는, try-catch 블록 바깥에 있는 다음 문장부터 프로그램이 계속 실행됩니다.
실행 결과
We are just printing the stack trace.
ArithmeticException is handled. But take care of the variable "c"
Value of c is : 0
java.lang.ArithmeticException: / by zero
at ArithmeticExceptionTest.main(ArithmeticExceptionTest.java:6)추가 팁: 예외 발생 자체를 예방하기
try-catch로 예외를 처리하는 것 외에도, 나눗셈을 수행하기 전에 분모가 0인지 미리 검사하면 예외 발생 자체를 방지할 수 있습니다.
if (a != 0) {
c = b / a;
} else {
System.out.println("분모는 0일 수 없습니다.");
}이처럼 사전 검증과 예외 처리를 적절히 조합하면 더욱 견고하고 안정적인 Java 프로그램을 작성할 수 있습니다.