JAVA/수업 복습

자바 공부기록 54 - Exception 예외

본이qq 2022. 5. 12. 14:13

●예외(Exception) 처리
-에러(Error) : 문법적으로 잘못된것, 에러가 존재하는 경우 컴파일이 안되어서 실행 자체가 될 수 없음
-예외(Exception) : 실행중 발생한 오류, 특정 상황 또는 조건이 만족되는 경우 오류가 발생하여 프로그램이 실행 중간에 종료되는 현상

-예외는 다양한 상황에 대해서 발생하는 현상으로 모든 예외를 대처할 수 없습니다
-다만, 예외가 발생한 경우 프로그램이 종료되지 않고 저장과 같은 기능을 제공할 수 있어야합니다
 (예외가 발생해도 프로그램이 강제 종료되지 않고 사용자에게 선택권 또는 처리 기회를 주는 것을 말합니다
-예외처리 : 예외가 발생한 경우 프로그램이 강제 종료되지 않도록 방지 또는 처리하는 것

 

Surround with try/catch

-try 구문안에서 예외가 발생하면, catch의 매개변수에 그 예외에 해당하는 객체가 있는지
 확인하고 있으면 해당 catch 구문을 실행합니다. 
-Exception e 는 모두를 포함 - 수용하는 최상위 예외 클래스이며, 다중 예외처리시
 가장 마지막에 위치시킵니다.

-다중 예외처리의 표현시 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
package days32;
 
public class Exception02 {
 
    public static void main(String[] args) {
        System.out.println(1);
        System.out.println(2);
        try {
            System.out.println(3/0);
            System.out.println(4);
            //try 구문에 있는 명령이라도 에러가 발생한 구문 다음에 위치하는 명령은 실행하지 않습니다.
        }catch( ArithmeticException e){
            e.printStackTrace();   // java.lang.ArithmeticException: / by zero
            e.getMessage(); //at days32.Exception02.main(Exception02.java:9)
            
            System.out.println("5 - 예외처리 1");
        
        }catch( Exception e) {
            System.out.println("5 - 예외처리 2");
        }
 
}
}
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
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
57
58
59
60
61
package days32;
 
import java.text.ParseException;
 
public class Exception03 {
 
    public static void main(String[] args) {
        
        ArithmeticException a = new ArithmeticException( "ArithmeticException 고의발생" ); 
        // a : 예외(오류) 객체
        try {
                //예외(오류)의 강제발생
                throw a; 
        }catch(ArithmeticException e) {
            System.out.printf("ArithmeticException - ");
            System.out.println("에러 메시지 : " + e.getMessage());
        }catch(RuntimeException e) {
            System.out.printf("RuntimeException - ");
            System.out.println("에러 메시지 : " + e.getMessage());
        }catch(Exception e) {
            System.out.printf("Exception - ");
            System.out.println("에러 메시지 : " + e.getMessage());
        }
        
        RuntimeException b = new RuntimeException( "RuntimeException 고의발생" ); 
        // b : 예외(오류) 객체
        try {
                //예외(오류)의 강제발생
                throw b; 
        }catch(ArithmeticException e) {
            System.out.printf("ArithmeticException - ");
            System.out.println("에러 메시지 : " + e.getMessage());
        }catch(RuntimeException e) {
            System.out.printf("RuntimeException - ");
            System.out.println("에러 메시지 : " + e.getMessage());
        }catch(Exception e) {
            System.out.printf("Exception - ");
            System.out.println("에러 메시지 : " + e.getMessage());
        }
        
        ParseException c = new ParseException( "ParseException 고의발생",0 ); 
        // b : 예외(오류) 객체
        try {
                //예외(오류)의 강제발생
                throw c; 
        }catch(ArithmeticException e) {
            System.out.printf("ArithmeticException - ");
            System.out.println("에러 메시지 : " + e.getMessage());
        }catch(RuntimeException e) {
            System.out.printf("RuntimeException - ");
            System.out.println("에러 메시지 : " + e.getMessage());
        }catch(ParseException e) {
            e.printStackTrace();
        }catch(Exception e) {
            System.out.printf("Exception - ");
            System.out.println("에러 메시지 : " + e.getMessage());
        }
 
}
}
 
cs

->예외(오류) 객체 생성시 new 생성자 초기값으로 에러 메세지를 지정할 수 있습니다.

 

 

 

 

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public static void main(String[] args) {
        method1();
    }
 
public static void method1() {
        method2();
    }
 
private static void method2() {
        throw new Exception();
    }
 
 
 
cs

-> method2() 메소드 내에 throw new Exception();에 에러

-> method2() 메소드 내에서 try / catch 로 직접 예외 처리를 해주던가, throw 처리를 해서 

    해당 메소드를 호출한 지점으로 예외 처리의 책임을 전가하던가 해야함

 

 

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public static void main(String[] args) {
        method1();
    }
 
public static void method1() {
        method2();
    }
 
private static void method2() throws Exception  {
        throw new Exception();
    }
 
 
 
cs

->throw 처리를 하고 난 후에는 method1() 메소드 내에 있는 method2()에 빨간줄이 뜸

-> 마찬가지로 method1() 에서 try / catch 로 직접 예외 처리를 해주던가, throw 처리를 해서 

    해당 메소드를 호출한 지점으로 예외 처리의 책임을 전가하던가 해야함

 

 

 

 

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public static void main(String[] args) {
    try {
        method1();
    } catch (Exception e) {
        e.printStackTrace();
     }
    }
 
public static void method1() throws Exception {
        method2();
    }
 
private static void method2() throws Exception  {
        throw new Exception();
    }
 
 
 
cs

->method1() 에서 throw 처리를 하고, method1()을 호출하고 있는 main 메소드 지점에서 

  try/catch로 직접 예외처리

 

 

 

 Surround with try/catch

 

-순수한 아라비아기호로 문자열을 입력받아서 숫자로 변환하는 코드를 작성하세요
입력내용중 숫자가 아닌 다른 것이 입력되면 다시 입력하라는 메세지와 함께 입력받는 코드가 실행되게 합니다. 
Integer.parseInt() 숫자가 아닌 글자를 정수로 변환하려고 하면 예외가 발생합니다.
최종 출력 : "입력한 숫자는 XX입니다"

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public static void main(String[] args) {
        int num;
        Scanner sc = new Scanner(System.in);
        System.out.print("정수를 입력하세요");
 
 
        while(true) {
            try {
                num = Integer.parseInt(sc.nextLine());
                break;
            }catch(NumberFormatException e) {
                System.out.print("정수를 입력하지 않았습니다. 다시 입력하세요.");
            }
        }
        
        System.out.println("입력한 숫자는 " + num + "입니다." );
        
cs

-> Integer.parseInt로 입력받기

 

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public static void main(String[] args) {
        int num;
        Scanner sc = new Scanner(System.in);
        System.out.print("정수를 입력하세요");
 
 
    while(true) {            
            try {
                num = sc.nextInt();
                break;
            }catch(InputMismatchException e) {
                System.out.println("정수가 아닌 잘못된 타입이 입력되었습니다.");
                //키보드 버퍼에 남아있는 문자열(엔터 등)의 값을 제거
                sc.nextLine(); //입력 버퍼를 비움, 이 코드가 없으면 위 출력값이 무한 실행됨
            }
        }
        System.out.println("입력한 숫자는 " + num + "입니다." );
    }
 
}
cs

-> sc.nextInt();로 입력받기 

중요 : 꼭 sc.nextLine(); 으로 입력 버퍼를 비워줘야함