언어/자바

예외처리(exception)

ballde 2021. 9. 16. 21:07

예외

입력 값에 대한 처리 불가능하거나, 참조된 값이 잘못된 경우 등 정상적인 프로그램의 흐름을 어긋나는 것

에러

시스템에 무엇인가 비정상적인 상황이 발생한 경우

 

Checked Exception / Unchecked Exception

checked Exception

  • RuntimeException을 상속하지 않는 클래스
  • 명시적으로 처리해야함 - checked

이 코드에서는 컴파일 시점에 이미 애러발생

아래 코드와 같이 반드시 예외 처리해줘야함

private void throwExceptionExample(String file, String targetFile) throws IOException {
        BufferedReader reader = null;
        PrintWriter writer = null;
        try {
            reader = new BufferedReader(new FileReader(file));
            writer = new PrintWriter(targetFile);
            String data = null;
            int line = 1;
            while((data = reader.readLine()) != null) {
                if (data.isEmpty())
                    continue;
                writer.println(line + data);
                line ++;
            }
        } finally {
            if (reader != null) reader.close();
            if (writer != null) writer.close();

        }
    }

예외처리 해줄 방법

  1. try - catch - final
  2. throws
  3. throw

unchecked exception

RuntimeExceptoin을 상속한 클래스

exception 전략

예외 처리

  • 예외 복구
private void throwExceptionExample(String file, String targetFile) {
        BufferedReader reader = null;
        PrintWriter writer = null;
        try {
            reader = new BufferedReader(new FileReader(file));
            writer = new PrintWriter(targetFile);
            String data = null;
            int line = 1;
            while((data = reader.readLine()) != null) {
                if (data.isEmpty())
                    continue;
                writer.println(line + data);
                line ++;
            }
        } catch(Exception e) {
            e.printStackTrace();
        } finally {
            if (reader != null) reader.close();
            if (writer != null) writer.close();
            
						// 예외가 발생해도 진행됨 
        }
    }
  • 예외 처리 회피
private void throwExceptionExample(String file, String targetFile) throws IOException {
        BufferedReader reader = null;
        PrintWriter writer = null;
        try {
            reader = new BufferedReader(new FileReader(file));
            writer = new PrintWriter(targetFile);
            String data = null;
            int line = 1;
            while((data = reader.readLine()) != null) {
                if (data.isEmpty())
                    continue;
                writer.println(line + data);
                line ++;
            }
        } finally {
            if (reader != null) reader.close();
            if (writer != null) writer.close();
            
        }
    }

// 예외가 발생하면 throws를 통해 호출한 쪽으로 예외를 던지고 그 처리를 회피
  • 예외 전환
private void throwExceptionExample(String file, String targetFile) {
        BufferedReader reader = null;
        PrintWriter writer = null;
        try {
            reader = new BufferedReader(new FileReader(file));
            writer = new PrintWriter(targetFile);
            String data = null;
            int line = 1;
            while((data = reader.readLine()) != null) {
                if (data.isEmpty())
                    continue;
                writer.println(line + data);
                line ++;
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
						throw new CustomIoException();
        }
    }

// 예외를 잡아서 다른 예외를 던짐
호출한 쪽에서 예외를 받아서 처리할 때 좀더 명확하게 인지할 수 있도록 돕기 위한 방법

보통 복구하지 않고 일반적인 코드의 흐름으로 제어함

Member member = new Member(null, "pwd", "email");
try {
    Long id = member.getId();
    // 로직 
} catch (Exception e) {
    Long id = member.getId();
    // 로직
}

-------------------------------------------

Member member = new Member(null, "pwd", "email");
if (member.getId() == null) {
    // 로직
} else {
    // 로직
}

예시) 유니크한 key가 중복돼서 SQLException을 발생시키는 경우 복구전략 가져가기 힘듦 → runtimeException발생시키고 정확한 메세지날림

 

checked Exception 전략

private void throwExceptionExample(String file, String targetFile) {
  BufferedReader reader = null;
  PrintWriter writer = null;
  try {
      reader = new BufferedReader(new FileReader(file));
      writer = new PrintWriter(targetFile);
      String data = null;
      int line = 1;
      while((data = reader.readLine()) != null) {
          if (data.isEmpty())
              continue;
          writer.println(line + data);
          line ++;
      }
  } catch (FileNotFoundException e) {
      throw new CustomFileNotFoundException();
  } catch (IOException e) {
      throw new CustomIoException();
  }
}

복구 전략이 좋지만 현실은 쉽지 않으므로

그냥 throws로 무의미하고 반복적인 예외를 던지는 checkedException보다

uncheckedException을 통해서 구체적으로 예외처리를 하라!!

'언어 > 자바' 카테고리의 다른 글

GC에 대해서 좀 더 살펴보자  (0) 2022.07.05
열거형(enum)  (0) 2021.09.16
자바 - 제네릭(Generic)  (0) 2021.09.13
직렬화 (Serialization) 와 역직렬화(Deserialization)  (0) 2021.09.13
thread에 대해서!  (0) 2021.09.11