java

Exception, 예외

1+1은? 2013. 7. 25. 16:50

Exception, 예외

 : 런타임 중 특정 상황에서 발생하는 에러를 말한다. 런타임 에러와 같은 의미로 봐도 된다.

 : 특정작업에서는 예외처리를 명시하지 않으면 컴파일 에러가 발생한다.

 

※ 반드시 예외처리를 해야 하는 경우

1. 네트워크 입출력

2. 데이터베이스 입출력

3. 메모리 입출력

4. 파일 입출력

5. 메서드에서 예외를 미룰 때

 

 

 

■ try catch

 

1
2
3
4
5
6
7
8
9
try { //비즈니스코드 블럭
   ... 
} catch(Exception e) { //예외처리코드 블럭, 예외 발생 시에만 실행
   ... 
} finally {
   ...
}
 
//finally : try, catch 뒤에 오며 예외 발생 여부와 관계없이 무조건 실행된다.

 

 

 

1
2
3
4
5
6
7
try {
    throw new Exception("내가 만든 예외"); //Exception 강제 발생
 
} catch (Exception e) //try절에서 던진(발생한) 예외를 처리하는 블럭
{
    System.out.println(e);
}

 

 

ArrayIndexOutOfBoundsException의 경우 배열의 범위를 초과할 때 발생하는 예외인데

아래처럼 코드작성 시 해당 예외가 발생할 것을 예측하여 작성할 수 있다.

 

1
2
3
4
5
6
7
8
9
int[] nums = new int[] {10, 20, 30, 40, 50};
 
System.out.print("보고싶은 인덱스 : ");
int index = scan.nextInt();
 
if(index >= 0 && index <=4)
    System.out.println(nums[index]);
else //범위 초과 시
    System.out.println("올바른 색인번호를 입력하세요.");

 

 

 

하지만 우리가 모든 경우의 수를 예측하여 그에 해당하는 코드를 만드는 것은 불가능하다.

따라서 다음처럼 작성하면 모든 예외를 처리할 수 있게 된다.

 

1
2
3
4
5
6
7
8
try {
    System.out.println(nums[index]);
 
} catch (ArrayIndexOutOfBoundsException e) { // Exception 으로 대체가능
                                                // Exception : 모든 예외
    System.out.println(e); // 발생한 예외의 메시지를 콘솔에 출력
    System.out.println("올바른 색인번호를 입력하세요.");
}

 

 

 

 

 

■ throw / throws

 : 예외 미루기

 : 예외가 발생했을 때 발생한 지역이 아닌 호출한 지역에서 예외를 처리한다.

 

다음은 main 메서드에서 m01() 메서드를 호출했을때 발생한 예외를 main에서 처리하는 예제다.

 

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
class Excep {
    public void m01() {
        int[] nums = new int[] { 1 };
        try {
            System.out.println(nums[2]);
            // ArrayIndexOutOfBoundsException 발생
            // new ArrayIndexOutOfBoundsException(); : 1. 예외 객체 생성
            // throws new ArrayIndexOutOfBoundsException : 2. 예외객체를 던진다.
        } catch (Exception e) {
            throw e; // 이 메서드를 호출한 지역이 예외를 받는다
        }
    }
}
 
public class Test {
    public static void main(String[] args) {
        Excep ex = new Excep();
 
        try {
            ex.m01();
        } catch (Exception e) {
            System.out.println("메서드를 호출한 지점");
        }
    }
}

 

 

하지만 어차피 예외를 미룰거라면 try catch를 생략하는 방법이 있다.

여기선 throws 키워드를 사용한다.

 

1
2
3
4
5
6
class Excep {
    public void m01() throws Exception {
        int[] nums = new int[] {1};
        System.out.println(nums[2]);
    }
}

 

 

 

 

■ 다중 catch

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
try {
    int[] nums = { 10, 20, 30 };
    System.out.println(nums[5]); // ArrayIndexOutOfBoundsException
 
    Random rnd = null;
    System.out.println(rnd.nextInt()); // NullPointerException
 
} catch (ArrayIndexOutOfBoundsException e) {
    System.out.println("인덱스범위에러");
 
} catch (NullPointerException e) {
    System.out.println("null에러");
}
// 또 다른 예외 발생?
catch (Exception e) {
    // 던진 객체를 받을 수 있는 클래스가 없다면 부모클래스인 Exception에 업캐스팅으로 받는다.
    System.out.println("범용적 에러");
}

 

 

 

 

■ 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
50
51
52
53
54
55
56
package old3;
 
public class Ex94_try {
    public static void main(String[] args) {
 
        //예외 코드
        // A001 : 배송 중 제품 파손
        // A002 : 배송 중 날짜 지연
        // A003 : 배송 중 잘못 배송
        // B001 : 사용 중 제품 불량
        // B002 : 사용 중 제품 오작동
         
        System.out.println("고객이 제품을 주문..");
         
        System.out.println("1. 주문접수 완료");
        System.out.println("2. 제품 포장");
        System.out.println("3. 제품 발송");
         
        System.out.println("고객이 제품을 수령..");
         
         
        try {
            System.out.println("제품파손 발견"); //A001
             
            throw new MyShopException("A001");
         
        } catch (MyShopException e) {
 
            System.out.println("예외 코드 : " + e);
            System.out.println("내선 번호 : " + e.checkNumber());
        }
    }
}
 
 
//사용자 정의 예외 클래스(Exception 파생클래스)
class MyShopException extends Exception {
    //예외 코드 관리-> 담당 상담원 안내
    private String code; //예외코드
     
    MyShopException(String code) {
        this.code = code;
    }
 
    //내선번호
    public String checkNumber() {
        String number = "";
        if (this.code.equals("A001")) number = "100";
        else if (this.code.equals("A002")) number = "110";
        else if (this.code.equals("A003")) number = "120";
        else if (this.code.equals("B001")) number = "200";
        else if (this.code.equals("B002")) number = "210";
         
        return number; //생성자로 받아온 Exception code를 비교해 해당 문자열을 리턴하는 메서드
    }
}