nme.kr

문서의 이전 판입니다!


Ch.11 예외처리

예외처리

try ~catch문의 구조

try {
    // 예외가 발생할 가능성이 있는 문장 코드
} catch (Exception1 e1) {
    // Exception1이 발생할 경우, 실행될 문장
} catch (Exception1 e2) {
    // Exception2이 발생할 경우, 실행될 문장
...
} catch (ExceptionX eX){
    // ExceptionX가 발생할 경우, 실행될 문장
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
package chapter11;
 
public class ExceptionEx0 {
 
    public static void main(String[] args) {
        System.out.println(1);
        System.out.println(2);
        System.out.println(3/0);
        System.out.println(4);
        System.out.println(5);
        System.out.println(6);
    }
     
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
package chapter11;
 
public class ExceptionEx {
 
    public static void main(String[] args) {
        System.out.println(1);
        try {
            System.out.println(2);
            System.out.println(3/0);
            System.out.println(4);
        } catch(ArithmeticException e) {
            System.out.println(5);
        }
        System.out.println(6);
    }
     
}

try 블록 안에서 예외가 발생한 경우
- 발생한 예외와 일치하는 catch 문이 있는지 확인한다.
- 만약 일치하는 catch문이 있다면, 해당 catch문의 블럭 내의 실행문을 실행하고 전체 try-catch 구문이 종료된다. 만약 일치하는 catch문이 없으면 예외 처리를 하지 못한다.
try 블록 안에서 예외가 발생하지 않은 경우
- catch 구문을 모두 확인하지 않고, 전체 try-catch 구문이 종료된다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
package chapter11;
 
public class ExceptionEx2 {
 
    public static void main(String[] args) {
        System.out.println(1);
        try {
            System.out.println(2);
            System.out.println(3);
            System.out.println(4);
        } catch(ArithmeticException e) {
            System.out.println(5); // Death 코드 (실행될 일이 없다)
        }
        System.out.println(6);
    }
     
}

:wr:다중 catch문

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
package chapter11;
 
public class ExceptionEx4 {
 
    public static void main(String[] args) {
         
        try {
            int[] arr = {1,2,3};
            System.out.println(arr[2]);
            System.out.println(3/1);
            Integer.parseInt("a");
        } catch(ArithmeticException e) {
            System.out.println("0으로 나눌 수 없음");
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("인덱스 범위 초과");
        }
    }
     
}

catch 문의 배치 순서
자식 Exception > Exception 순으로 배치

:wr:finally문

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
package chapter11;
 
public class ExceptionEx3 {
 
    public static void main(String[] args) {
        System.out.println("DB연결 시작");
        try {
            System.out.println("DB작업");
            System.out.println(3/0);
        } catch(Exception e) {
            System.out.println("DB작업 중 예외발생");
        } finally {
            System.out.println("DB연결 종료");
        }
    }
     
}

예외 강제 발생

throw 키워드 사용
throw new Exception( “ 예외 발생 ”);

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
package chapter11;
 
public class ExceptionEx5 {
 
    public static void main(String[] args) {
        System.out.println("프로그램 시작");
        try {
            throw new Exception("예외 발생");
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        System.out.println("프로그램 종료");
    }
     
}

예외 떠넘기기

메서드에서 예외 선언

void 메서드명() throws Exception1, Exception2... {
...
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
package chapter11;
 
public class ExceptionEx6 {
 
    public static void main(String[] args) {
        try {
            first();
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }
     
    static void first() throws Exception {
        second();
    }
     
    static void second() throws Exception {
        throw new Exception("예외 발생");
    }
     
}

:wr:예외 재발생

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
package chapter11;
 
public class ExceptionEx7 {
 
    public static void main(String[] args) throws Exception {
        try {
            first();
        } catch (Exception e) {
            System.out.println("main() 예외 처리");
            System.out.println(e.getMessage());
            throw e;
        }
    }
     
    static void first() throws Exception {
        try {
            second();
        } catch (Exception e) {
            System.out.println("first() 예외 처리");
            throw e; // 예외 재발생
        }
    }
     
    static void second() throws Exception {
        try {
            throw new Exception("예외 발생");
        } catch (Exception e) {
            System.out.println("second() 예외  처리");
            throw e; // 예외 재발생
        }
    }
     
}

1
2
3
4
5
6
7
8
9
10
    public static void main(String[] args) throws Exception {
        try {
            first();
        }
        catch (Exception e) {
        System.out.println("Main() 예외 처리");
        System.out.println(e.getMessage());
        throw e;
    }
}

사용자 정의 예외 클래스

class 클래스명 extends Exception {
     클래스명 (String msg) {
           super(msg);
      }
 }

LoginException.java

1
2
3
4
5
6
7
8
package chapter11;
 
public class LoginException extends Exception {
 
    LoginException(String msg) {
        super(msg);
    }
}

ExceptionEx8.java

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
package chapter11;
 
import java.util.Scanner;
 
public class ExceptionEx8 {
     
    static String user_id = "seo";
    static String user_pw = "smg1234";
 
    public static void main(String[] args) throws Exception {
         
        try {
            Scanner scan = new Scanner(System.in);
            System.out.print("아이디 : ");
            String input_id = scan.nextLine();
             
            System.out.print("비밀번호 : ");
            String input_pw = scan.nextLine();
             
            if (!user_id.equals(input_id)) {
                throw new LoginException("아이디가 올바르지 않습니다.");
            } else if (!user_pw.equals(input_pw)) {
                throw new LoginException("비밀번호가 올바르지 않습니다.");
            } else {
                System.out.println("로그인 성공");
            }
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
         
    }
     
     
}

:wr:try-with-resource

기존 try~catch 방식

FileInputStream is = null;
BufferedInputStream bis = null;
try {
is = new fileInputStream("파일명")
bis = new BufferdInputStream(is);
int data = -1;
while((data = bis.read()) !=-1){
	System.out.print((char)data);
}
} finally {
// close 메서드 호출
if ((is != null) is.close();
if (bis != null) bis.close();
}

try-with-resource 방식

try(
	FileInputStream is = new FileInputStream("파일명");
	BufferedInputStream bis = new BufferdInputStream(is)
) {
	int data = -1;
	while ((data = bis.read()) != -1) {
	System.out.print((char) data);
}
} catch (IOException e) {
e.printStackTrace();
}