Java 다중 예외 처리 마스터: 단일 Catch 블록으로 여러 예외 잡기
Java 다중 예외 처리 마스터하기
단일 catch 블록으로 여러 예외 잡아 코드 간소화하고 흔한 함정 피하는 법 알아보기.
Java 7 전에는 처리 로직이 동일해도 각 예외 타입별 별도 catch 블록 작성 필요.
다음 시나리오 고려.
예제 1: 별도 catch 블록
class Main { public static void main(String[] args) { try { int[] array = new int[10]; array[10] = 30 / 0; } catch (ArithmeticException e) { System.out.println(e.getMessage()); } catch (ArrayIndexOutOfBoundsException e) { System.out.println(e.getMessage()); } } }
출력
/ by zero
이 예제에서 두 가지 개별 문제 발생 가능:
ArithmeticException – 0으로 나누기.
ArrayIndexOutOfBoundsException – 10개 요소 배열에서 인덱스 10 접근.
두 catch 블록이 같은 동작 수행, 코드 중복 발생.
단일 블록으로 여러 예외 잡기
Java SE 7부터 파이프(|) 구분자로 여러 예외 타입을 한 catch 블록에 결합 가능.
문법:
try { // 코드 } catch (ExceptionType1 | ExceptionType2 ex) { // 핸들러 }
예제 2: 멀티-catch 블록
class Main { public static void main(String[] args) { try { int[] array = new int[10]; array[10] = 30 / 0; } catch (ArithmeticException | ArrayIndexOutOfBoundsException e) { System.out.println(e.getMessage()); } } }
출력
/ by zero
핸들러 병합으로 코드 깔끔해지고 바이트코드 작아지며 유지보수 용이.
참고: 멀티-catch에서 매개변수 암시적 final, 재할당 불가.
기반 예외 클래스 사용
여러 잡는 예외가 공통 조상 공유 시 각 하위 클래스 나열 대신 조상 잡기 가능.
예제 3: 기본 Exception 클래스 잡기
class Main { public static void main(String[] args) { try { int[] array = new int[10]; array[10] = 30 / 0; } catch (Exception e) { System.out.println(e.getMessage()); } } }
출력
/ by zero
Java 모든 특정 예외가 Exception 확장하므로 이 단일 catch 블록이 위 모든 시나리오 처리.
기반 예외 이미 잡혔으면 같은 catch에 하위 클래스 포함 시 컴파일 에러.
예제 4: 기반과 자식 예외 잘못된 조합
class Main { public static void main(String[] args) { try { int[] array = new int[10]; array[10] = 30 / 0; } catch (Exception | ArithmeticException | ArrayIndexOutOfBoundsException e) { System.out.println(e.getMessage()); } } }
출력
Main.java:6: error: Alternatives in a multi-catch statement cannot be related by subclassing
ArithmeticException과 ArrayIndexOutOfBoundsException이 Exception 하위 클래스라 언어 규칙 위반으로 에러 발생.