Java 예외 2 - 예외 던지기

별의개발자커비·2023년 2월 16일
0

Java

목록 보기
47/71
post-thumbnail

예외의 강제?

API를 사용할 때 설계자의 의도에 따라서 예외를 반드시 처리해야 하는 경우가 있다.

예외 처리 방법: throw와 throws

  • 책임의 전가
    : 다음 사용자에게 예외 처리의 책임을 넘기는 것이다.
  • ThrowExceptionDemo를 쓰려면 클래스C를 사용해야하고, 클래스 C를 쓰려면 클래스 B를 사용해야 함.
  • 이 때, 최초로 사용해야하는 클래스 B에서 예외처리가 어려운 경우 클래스 C로 예외를 throws할 수 있음.

1. 클래스B->C로 throws한 경우

import java.io.*;

class B{
    void run() throws FileNotFoundException, IOException { // 1. throws + 오류 예외 상황
			// run이라는 메소드 내부적으로 FileNotFoundException가 발생할 수 있다는 것을 강력히 암시해주는 것
			// = 이 예외에 대응할 것을 강제하는 것
			public static void main(String[] args) {
        BufferedReader bReader = null;
        String input = null;
				bReader = new BufferedReader(new FileReader("out.txt"));
        // try {						// 3. 그러면 여기에서는 안대응해줘도 됨
        //     bReader = new BufferedReader(new FileReader("out.txt"));
        // } catch (FileNotFoundException e) {
        //     e.printStackTrace();
        // }
				
				// IOException도 마찬가지
				input = bReader.readLine();
        // try{ 
        //     input = bReader.readLine();
        // } catch (IOException e){ 
        //     e.printStackTrace();
        // }       
        System.out.println(input); 
    	}
    }
}
class C{
    void run(){
        B b = new B();
			try { // 2. try catch를 해서 여기서 예외 상황 대응해주기
            b.run();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

class ThrowExceptionDemo {

    public static void main(String[] args) {
        C c = new C();
         c.run();
    }
}

2. 클래스 C에서 ThrowExceptionDemo로 throws 한 경우

import java.io.*;

class B{
    void run() throws FileNotFoundException, IOException { 
			public static void main(String[] args) {
        BufferedReader bReader = null;
        String input = null;
				bReader = new BufferedReader(new FileReader("out.txt"));
				input = bReader.readLine();  
        System.out.println(input); 
    	}
    }
}
class C{
    void run() throws FileNotFoundException, IOException{
        B b = new B();
				b.run();
			// try { 
			// b.run();
			// } catch (FileNotFoundException e) {
			// e.printStackTrace();
			// } catch (IOException e) {
			// e.printStackTrace();
			// }
			// }
}

class ThrowExceptionDemo {

    public static void main(String[] args) {
         C c = new C();
         try {
            c.run();
        } catch (FileNotFoundException e) {
            System.out.println("out.txt 파일은 설정 파일 입니다. 이 파일이 프로잭트 루트 디렉토리에 존재해야 합니다.");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }   
}

Thread.sleep 쓸 때의 InterruptedException 예외 처리

http://happinessoncode.com/2017/10/09/java-thread-interrupt/

profile
비전공자 독학러. 일단 쌔린다. 개발 공부👊

0개의 댓글