Notice
Recent Posts
Recent Comments
«   2024/09   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30
Archives
Today
Total
관리 메뉴

충분히 쌓여가는

11.3 예외 종류에 따른 처리 - 예외 순서, 다중 catch 본문

이것이 자바다/11 예외 처리

11.3 예외 종류에 따른 처리 - 예외 순서, 다중 catch

빌드이너프 2024. 4. 8. 11:35

다중 catch

try 블록에는 다양한 종류의 예외가 발생할 수 있다

예외에 따라 예외 처리 코드를 다르게 작성할 수 있다

 

catch 블록이 여러 개라 할지라도 catch 블록은 단 하나만 실행된다

: try 블록에서 동시 다발적으로 예외가 발생하지 않으며, 하나의 예외가 발생하면 즉시 실행을 멈추고 해당 catch 블록으로 이동하기 때문

 

예제

배열의 인덱스가 초과되었을 경우 발생하는 ArrayIndexOutOfBoundsException과

숫자 타입이 아닐 때 발생하는 NumberFormatException을 각각 다르게 예외 처리한다

package ch11.sec02.exam03;

import java.util.Iterator;

public class ExceptionHandlingExample {
	public static void main(String[] args) {
		String[] array = {"100", "1oo"};
		
		for(int i=0; i<=array.length; i++) {
			try {
				int value = Integer.parseInt(array[i]);
				System.out.println(value);
			} catch(ArrayIndexOutOfBoundsException e) {
				System.out.println("배열 인덱스 초과: " + e.getMessage());
			} catch(NumberFormatException e) {
				System.out.println("숫자로 변환할 수 없음: " + e.getMessage());
			}
		}
	}
}
100
숫자로 변환할 수 없음: For input string: "1oo"
배열 인덱스 초과: Index 2 out of bounds for length 2

 

 

 

예제

처리해야할 예외 클래스들이 상속 관계에 있을 떄

하위 클래스 catch 블록을 먼저 작성하고, 상위 클래스 catch 블록을 나중에 작성해야 한다

(catch 블록은 위에서 차례대로 검사 대상이 되는데, 상위 클래스 catch 블록이 먼저 검사 대상이 되면 안된다)

package ch11.sec03.exam02;

public class ExceptionHandlingExample {
    public static void main(String[] args) {
        String[] array = {"100", "1oo"};

        for(int i=0; i<=array.length; i++) {
            try {
                int value = Integer.parseInt(array[i]);
                System.out.println(value);
            } catch(ArrayIndexOutOfBoundsException e) {
                System.out.println("배열 인덱스 초과: " + e.getMessage());
            } catch(Exception e) { // 상위 예외 클래스는 아래 쪽에 작성
                System.out.println("숫자로 변환할 수 없음: " + e.getMessage());
            }
        }
    }
}
100
숫자로 변환할 수 없음: For input string: "1oo"
배열 인덱스 초과: Index 2 out of bounds for length 2

 

 

예제

두 개 이상의 예외를 하나의 catch 블록으로 동일하게 예외처리

catch 블록에 예외 클래스르 기호 |로 연결

package ch11.sec03.exam03;

public class ExceptionHandlingExample {
	public static void main(String[] args) {
		String[] array = {"100", "1oo", null, "200"};
		
		for(int i=0; i<=array.length; i++) {
			try {
				int value = Integer.parseInt(array[i]);
				System.out.println(value);
			} catch(ArrayIndexOutOfBoundsException e) {
				System.out.println("배열 인덱스 초과: " + e.getMessage());
			} catch(NullPointerException | NumberFormatException e) { 
				System.out.println("데이터 문제가 있음: " + e.getMessage());
			}
		}
	}
}
100
데이터 문제가 있음: For input string: "1oo"
데이터 문제가 있음: Cannot parse null string
200
배열 인덱스 초과: Index 4 out of bounds for length 4

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

'이것이 자바다 > 11 예외 처리' 카테고리의 다른 글

11.6 사용자 정의 예외  (0) 2024.04.08
11.5 예외 떠넘기기 - throws  (0) 2024.04.08
11.2 예외 처리 코드  (0) 2024.04.08
11.1 예외와 예외 클래스  (0) 2024.04.08
이것이 자바다 11장 확인문제  (0) 2024.02.05