Java

[Java] Exception ( Error, Exception, 예외 처리, 예외 전가)

소댓 2023. 3. 27. 18:25

< Exception >

 

* 에러의 종류(Error / Exception)

1. Error : 치명적 오류

2. Exception : 가벼운 오류

   1) 예외 처리 : try, catch (+finally)

   2) 예외 전가 : throws > 메서드를 사용하는 사람이 자신의 환경에 맞게 이 예외를 처리하도록 예외를 전가 시키는 방법

 

* 예외의 종류

- nullpoint exeption / ArithmeticException / NumberFormatException / InterruptedException / ... 

 > Exception e : 항상 마지막에 놓고 사용한다. 모든 예외가 여기서 다 걸리기 때문에  모든 예외를 받아줄 존재  

 

- PrintStrackTrace : 어떤 예외인지 출력

 

 

 

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
package day18;
// 에러를 두 가지로 나누면..
 
// 1. Error : 치명적 오류
// 2. Exception : 가벼운 오류
    // 1. 예외 처리 : try ~~ catch
    // 2. 예외 전가 : 
import java.util.Random;
 
public class ExceptionEx1 {
public static void main(String[] args) {
    
 
//    Random rnd = new Random();
    Random rnd = null// 예외 일으키기(nullpoint exception)
    
    // try ~ catch : 예외가 던져지면(try) 잡는다.(catch)
    
 
        int a = 100;
    try { // 예상의심지역
        int value = rnd.nextInt(10);
    
        System.out.println("랜덤하게 뽑은 값 : "+value);
        System.out.println(a/value);
 
    } catch(ArithmeticException ae) { // 이런 예외라면 이렇게 해줘..
//        // 예외가 발생할 때 실행하는 코드
        // ae.printStackTrace(); // 어떤 문제인지 알려줌
        System.out.println("ArithmeticException 발생하면 이 부분의 코드가 실행");
        System.out.println("0으로 나눌 수 없습니다.");
    } catch(NullPointerException npe) {
        // npe.printStackTrace();
        System.out.println("널 포인터 익셉션 발생");
        System.out.println("참조변수에 null이 들어감");
    } catch(Exception e ) { // 항상 마지막에 놓고 사용한다. 모든 예외가 여기서 다 걸리기 때문에
        // 모든 예외를 받아줄 존재 : Exception(모든 예외의 조상)
        System.out.println("모든 예외는 여기서 다 걸림");
        System.out.println("이건 나도 모르는 Exception");
        e.printStackTrace();
    }
    // random이 0일 때, 오류 발생 > 수학에서 0으로 나누는 건 불가
    // : 이러한 에러는 syntax error가 아닌, Exception Error
}
}
 
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
package day18;
// 2. 예외 전가
public class ExceptionEx2 {
    static int plus(String x, String y) throws NumberFormatException{
        // 이 메서드를 사용하는 사람이 자신의 환경에 맞게 이 예외를 처리하도록
        // 예외를 전가 시키는 방법
        int a = 0, b = 0
        a = Integer.parseInt(x); // "10" ==> 10(문자를 숫자로 변환)
        b = Integer.parseInt(y); // "10" ==> 10(문자를 숫자로 변환)
        // 예외가 일어나면 메세지를 콘솔에 출력해..
        return a + b;
 
    }
    public static void main(String[] args) {
        
        String a = "10a"// 예외 발생
        String b = "20";
        int result = 0;
        // System.out.println(" a + b : "+(a+b));
        try {
            result = plus(a, b);
        } catch(NumberFormatException nfe) {
            System.out.println("올바르지 않은 숫자 형식입니다.");
        }
        System.out.println(" result : "+result); // result : 30
    }
    
}
 
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
package day18;
 
import java.io.IOException;
 
public class ExceptionEx3 {
    public static void main(String[] args) throws IOException{
        
        
        System.out.println("입력");
        
        try {
            int value = System.in.read(); // 예외가 일어날만한 변수
            System.out.println(value);
        } catch(IOException ie) { // system.in.read에서 발생 가능한 오류
            System.out.println("입출력 오류 발생했습니다.");
            ie.printStackTrace();
        } finally {
            // 예외가 있던 없던 반드시 실행되는 코드
            System.out.println("예외가 있던 없던 이 부분은 반드시 실행");
            // I/O, network db
            // 자원 반납하는 코드
 
        }
        
        int t = System.in.read();
        
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
        
    }
}
 
cs