try {
// 실행 코드
} catch (ExceptionType e) {
// 예외 처리
} finally {
// 예외 발생 여부와 관계 없이 실행
}
catch (ExceptionType1 | ExceptionType2 e) {
// 예외 처리
}
e.getMessage(): 간략한 에러 메시지 반환.e.getLocalizedMessage(): 동일한 기능.e.printStackTrace(): 예외 상황 메시지 강제 출력.Tip: 예외 처리로 프로그램 안정성 향상 및 디버깅 용이성 증가.
예제 코드
public class ExceptionHandlingExample {
public static void main(String[] args) {
try {
int[] numbers = {1, 2, 3};
int result = numbers[4]; // 배열 인덱스 초과 발생
System.out.println(result);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Array index out of bounds.");
} catch (Exception e) {
System.out.println("An unexpected error occurred.");
} finally {
System.out.println("This block always executes.");
}
divide(10, 0); // 산술 예외
}
private static void divide(int a, int b) {
try {
int result = a / b;
System.out.println(result);
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero.");
}
}
}
실행 결과
Array index out of bounds.
This block always executes.
Cannot divide by zero.