예외(exception)의 종류는 매우 다양하다.

 

예를 들어,

 

1. 숫자(number)를 입력해야 하는데 문자열(String)이 입력되었을 때

 

2. 배열(array)의 index 범위를 벗어났을 때

 

3. 사용하려는 class가 존재하지 않을 때

 

4. 접근하려는 위치에 file이 없을 때

 

등이 있다.

 

예외가 발생할 가능성이 있는 코드들을 적는다고 한다면, 어떤 형식으로 적어야 할까?

2가지 경우로 나눠서 그 형식에 대해 살펴보자.

 

1. 예외가 발생할 가능성이 있는 코드를 다른 코드들 안에 적을 때,

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
    try {
 
        exception이 발생할 가능성이 있는 코드
         
    } catch(예외클래스1 e) {        //예외가 발생했을 때!
        메시지 출력
    } catch(예외클래스2 e) {                    
        메시지 출력
    } catch(예외클래스3 e) {                    
        메시지 출력
    } finally {
        무조건 실행 (예외가 발생하든 안하든)
        //(복구 코드) - undo / rollback
    }
cs

 

2. 예외가 발생할 가능성이 있는 코드를 함수 안에 적을 때, 

 

1
2
3
static void func() throws 예외클래스 {
        exception이 발생할 가능성이 있는 함수
    }
cs

 

간단한 코드를 통해 예시를 들어보면,

 

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
package test;
 
public class Practice {
 
    public static void main(String[] args) {
    
        int[] array = { 1,2,3 };
        
        try {
            
            for (int i = 0; i < 4; i++) {         //array.length가 3인데, 인덱스 하나가 범위 초과
                System.out.println(array[i]);
            }
            
        } catch (ArrayIndexOutOfBoundsException e) {
            //메시지 출력 방식은 여러 가지가 있다.     //결과       
            System.out.println("배열 범위 초과");   // 배열 범위 초과 
            e.printStackTrace();                 
            System.out.println(e.getMessage());      //Index 3 out of bounds for length 3
        }
 
    }
 
}
 
cs

< console >

 

위 코드를 이어서 작성해보자.("finally"의 효과를 살펴보자)

 

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
31
32
33
34
35
36
37
38
39
package test;
 
public class Practice {
 
    public static void main(String[] args) {
    
        int[] array = { 1,2,3 };
        
        System.out.println("start ---");
        
        try {
            
            for (int i = 0; i < 4; i++) {         //array.length가 3인데, 인덱스 하나가 범위 초과
                System.out.println(array[i]);
            }
            
            System.out.println("process ---");   // for문에 exception이 존재해서 실행되지 않음
            
        } catch (ArrayIndexOutOfBoundsException e) {
            //메시지 출력 방식은 여러 가지가 있다.         //결과    
            System.out.println("배열 범위 초과");   // 배열 범위 초과 
            //e.printStackTrace();                 
            //System.out.println(e.getMessage());     //    Index 3 out of bounds for length 3
        
            return//프로그램이 끝남 -> 아래 "end ---"는 실행되지 않음
        
        } catch (Exception e) {    //다른 exc eption들의 경우
            e.printStackTrace(); 
        } finally {
            System.out.println("finally ---"); //return;에도 불구하고 반드시 실행됨
        }
        
        System.out.println("end ---"); //return;에 의해 실행되지 않음
        
 
    }
 
}
 
cs

 

이제 예외가 발생할 가능성이 있는 코드를 함수 안에 작성해보자.(func() 호출 부분은 생략)

 

1
2
3
4
5
6
7
8
static void func() throws IndexOutOfBoundsException {
        int[] num = { 1,2,3 };
        
        for (int i = 0; i < 4; i++) {
            System.out.println(num[i]);
        }
        
    }
cs

Exception의 종류별로 코드를 작성해보면 다음과 같다.

 

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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
//Exception 정리
        
        //NullPointerException - 데이터가 생성되어 있지 않음
        
        String str = null// String인 str이 비어 있다.
        
        try {
            System.out.println(str.length());
        } catch (NullPointerException e) {
            System.out.println("str이 null입니다.");
        }
    
        //ArrayIndexOutOfBoundsException - 배열의 범위를 초과
        
        int[] arr = {1,2,3};
        
        try {
            arr[3= 4;
        } catch(ArrayIndexOutOfBoundsException e) {
            System.out.println("배열 범위 초과");
        }
        
        //FileNotFoundException - 파일을 찾을 수 없음
        File f = new File("d:\\xxxxx");
        FileInputStream is;
        
        try {
            is = new FileInputStream(f);
        } catch (FileNotFoundException e) {
            System.out.println("파일을 찾을 수 없습니다.");
        }
        
        //StringIndexOutOfBoundsException - 글자가 존재하는 범위 밖임
        String str1 = "java";
        
        try {
        str1.charAt(4);
        } catch(StringIndexOutOfBoundsException e) {
            System.out.println("문자가 존재하지 않는 공간입니다.");
        }
        
        
        //NumberFormatException - 숫자가 들어와야 하는 자리에 문자가 들어옴
        
        try {
        int i = Integer.parseInt("12a3"); //숫자형의 문자열("123"과 같은)이 들어와야 하는데, 문자가 껴있음
        } catch (NumberFormatException e) {
            System.out.println("숫자가 아닌 글자가 있습니다.");
        }
cs

 

그런데, 각각의 exception의 종류와 관계없이 모두 "Exception"을 통해 예외를 나타내 줄 수 있다. 

즉, 정확하게 분류해서 코드를 작성하지 않아도 동일한 결과를 도출할 수 있다. 아래를 보자.

 

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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
//Exception 정리
        
        //NullPointerException - 데이터가 생성되어 있지 않음
        
        String str = null// String인 str이 비어 있다.
        
        try {
            System.out.println(str.length());
        } catch (Exception e) {
            System.out.println("str이 null입니다.");
        }
    
        //ArrayIndexOutOfBoundsException - 배열의 범위를 초과
        
        int[] arr = {1,2,3};
        
        try {
            arr[3= 4;
        } catch(Exception e) {
            System.out.println("배열 범위 초과");
        }
        
        //FileNotFoundException - 파일을 찾을 수 없음
        File f = new File("d:\\xxxxx");
        FileInputStream is;
        
        try {
            is = new FileInputStream(f);
        } catch (Exception e) {
            System.out.println("파일을 찾을 수 없습니다.");
        }
        
        //StringIndexOutOfBoundsException - 글자가 존재하는 범위 밖임
        String str1 = "java";
        
        try {
        str1.charAt(4);
        } catch(Exception e) {
            System.out.println("문자가 존재하지 않는 공간입니다.");
        }
        
        
        //NumberFormatException - 숫자가 들어와야 하는 자리에 문자가 들어옴
        
        try {
        int i = Integer.parseInt("12a3"); //숫자형의 문자열("123"과 같은)이 들어와야 하는데, 문자가 껴있음
        } catch (Exception e) {
            System.out.println("숫자가 아닌 글자가 있습니다.");
        }
cs

 

위 두 가지 방식의 코드의 실행 결과는 다음과 같다.

< console >

끝으로, while문을 이용하여 예외에 해당하지 않는 입력을 할 때까지 입력을 반복하게 하는 코드를 작성해보자.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
Scanner sc = new Scanner(System.in);
        
    
        int number = 0;
        while(true) {
            
        System.out.print("숫자를 입력하세요 >>");
        String strNum = sc.next();
        
        try {
            number = Integer.parseInt(strNum);
        } catch(Exception e) {
            System.out.println("숫자가 아닌 글자가 존재합니다.");    
            continue;
        }
        break;
        }
cs

< console >

숫자형으로 된 문자열을 입력해야 break되는 모습

'Java' 카테고리의 다른 글

날짜와 시간(Calendar class)  (2) 2022.12.26
정렬(Sorting) - 오름차순, 내림차순  (0) 2022.12.26
함수 사용  (4) 2022.12.26
break, continue  (0) 2022.12.23
반복문 - for, while, do - while  (2) 2022.12.22

+ Recent posts