[JAVA] Exception 예외처리


0. 숫자만 입력 예외 (문자 X)
int btn = 0;
while (true) {
try {
System.out.print("입력> ");
btn = Integer.parseInt(sc.nextLine());
} catch (NumberFormatException e) {
System.out.println("숫자만 입력해 주세요.");
}
}

1. InputMismatchException
 정수로 입력해야 하는데 문자를 입력한 경우 예외 발생
실습1
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
62
63
64
65
66
67
68
69
70
71
72
73
package com.ktds.jmj;
import java.util.InputMismatchException;
import java.util.Scanner;
public class InputMissmatchExceptionTest { // Scanner 할 때 많이 발생하는 예외
    public void start() {
        
        int number1 = 0;
        int number2 = 0;
        int number3 = 0;
        
        int currentStatus = 1;
        System.out.println("정수를 입력하세요!");
        Scanner input = new Scanner(System.in);
        int number=0;
        
        //사용자가 정수를 입력할 때 까지 반복한다.
        while (true){
            //예외가 발생할지 아닐지 모르지만, 우선 실행해본다.
            try { 
                //예외가 발생할 가능성이 있는 코드를 입력
                switch ( currentStatus ) {
                case 1 :
                    System.out.println("1번수");
                    number1 = input.nextInt();
                    currentStatus = 2;
                case 2 :
                    System.out.println("2번수");
                    number2 = input.nextInt();
                    currentStatus = 3;
                case 3 :
                    System.out.println("3번수");
                    number3 = input.nextInt();
                    currentStatus = 1;
                }
                number = input.nextInt();
                break;
            }
            
            //try 내부의 코드가 InputMismatchException 을 던진다면, 예외를 받아온다.
            //catch가 실행되는 동안은 Program 이 종료되지 않는다.
            catch ( InputMismatchException ime) {
                //스캐너의 버그를 해결하기 위한 코드
                input = new Scanner(System.in);
                System.out.println("잘못 입력했씁니다. 정수만 입력가능");
                
                /**
                 * 쓰면 안되는 코드
                 * 예외의 구체적인 정보를 알고싶을때 쓴다.
                 * 구체적인 정보를 알고 난뒤에는 반드시 지워야한다.
                 */
                ime.printStackTrace();
                
                // 애용해야하는 코드
                // 어떤 예외가 어떻게 발생했는지 간략히 알려준다
                System.out.println(ime.getClass().getName() + "예외가 " + ime.getMessage() + "때문에 발생했습니다.");
            }
        }    
            System.out.println("당신이 입력한 정수는 " + number + "입니다.");
    }
    
    public static void main(String[] args) {
        
        InputMissmatchExceptionTest test = new InputMissmatchExceptionTest();
        test.start();
    }
    
}
cs

2. ArithmeticException
정수를 0으로 나눌 경우 예외 발생
실습1
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
package com.ktds.jmj;
import java.util.Scanner;
public class ArtithmaticExceptionTest {
    
    public void start() {
        
        //import 단축키 ctrl + shift + o
        Scanner input = new Scanner (System.in);
        
        int numberOne = 0;
        int numberTwo = 0;
        double result = 0.0;
        
        System.out.println("첫번째 숫자를 입력하세요.");
        numberOne = input.nextInt();
        
        System.out.println("두번째 숫자를 입력하세요.");
        numberTwo = input.nextInt();
        
        try {
            result = numberOne / (double) numberTwo;
        }
        catch ( ArithmeticException ae ) {
            System.out.println(ae.getMessage());
        }
        System.out.println("결과는 " + result + " 입니다.");
        
    }
    public static void main(String[] args) {
        
        ArtithmaticExceptionTest test = new ArtithmaticExceptionTest();
        test.start();
    }
}
cs

3. NullPointerException
null reference를 참조할 경우 예외 발생
실습1
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
public class NullPointerExceptionTest {
   public void start(){
      
      String str = new String("BBB");
      
      for (int i = 0; i < 0; i++) {
         
         if(str!= null && str.equals("AAA")){ // Null 예외는 try catch걸지마....
            System.out.println("AAA 입니다.");
         }
         else {
            System.out.println("에러 입니다.");
         } 
      }  
   }
   
   public static void main(String[] args) {
      NullPointerExceptionTest test = new NullPointerExceptionTest();
      test.start();
   }
   
}
cs

4. ArrayIndexOutOfBoundException
배열의 범위를 벗어나서 접근한 경우 예외 발생
실습1
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
package com.ktds.jmj;
import java.util.ArrayList;
import java.util.List;
public class ArrayIndexOutOfBoundExceptionTest {
    
    public void start() {
        caseOne();
        caseTwo();
        
    }
    
    
    public void caseOne() {
        //배열을 사용함.
        int numbers[] = new int[5];
        
        for ( int i = 0; i <numbers.length; i++ ) { 
            numbers[i] = i;
        }
        
        try {
            numbers[5= 10;
        }
        catch ( ArrayIndexOutOfBoundsException aioobe ) {
            System.out.println(aioobe.getMessage() + "번 인덱스는 존재하지 않습니다.");
        }
        /*
         * 결과
         * ======================
         * 0 : 첫 번째 인덱스
         * 1 : 두 번째 인덱스
         * 2 : ........
         * 3 : ......
         * 4 : .....
         * 
         */
        for ( int number : numbers ) {
            System.out.println(number);
        }
        
    }
    
    public void caseTwo() {
        
        List<Integer> numbers = new ArrayList<Integer>();
        
        for ( int i = 0; i < 5; i++ ) {
            numbers.add(i);
        }
        
        for ( int i = 0; i < numbers.size(); i++){
            System.out.println(numbers.get(i));
        }
        /*
         * 결과
         * ======================
         * 0 : 첫 번째 인덱스
         * 1 : 두 번째 인덱스
         * 2 : ........
         * 3 : ......
         * 4 : .....
         * 
         */
        for ( int number : numbers ) {
            System.out.println(number);
        }
                
    }
    public static void main(String[] args) {
        
        ArrayIndexOutOfBoundExceptionTest test = new ArrayIndexOutOfBoundExceptionTest();
        test.start();
    }
}
cs

5. FileNotFoundException
파일을 찾을 수 없을 경우 예외 발생
실습1
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
package com.ktds.jmj;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
public class FileNotFoundExceptionTest { // 파일을 찾을 수 없을 때
    
    public void start() {
        
        File file = new File("D:\\isajkfslad.ddd");
        try {
            InputStream is = new FileInputStream(file);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }
    public static void main(String[] args) {
        
        FileNotFoundExceptionTest test = new FileNotFoundExceptionTest();
        test.start();
    }
}
cs


cf > NullCheck하는 방법
1
2
3
4
5
6
7
   public Scanner getScannerNullCheck() { // 디자인 패턴 중 하나이다.
        if (this.console == null){ // console은 Scanner로 입력받은 값.
            this.console = new Scanner(System.in);
        }
        return this.console;
    }
cs


출처: http://best421.tistory.com/10 [Updates available]

댓글