던지기

Java의 데이터 타입과 예외

Jim White

Java Developer

처리 옵션

  • 체크 예외는 "처리"가 필요합니다
    • 런타임 예외는 처리 선택 사항입니다
  • "처리" 옵션 두 가지
    • try/catch로 Exception을 잡아 대응 코드 작성
    • 예외를 "throw"하기
  • 예외 처리에는 try/catch가 선호됩니다
    • 항상 가능하진 않으며, 처리 로직을 통합하는 게 나을 때도 있습니다
Java의 데이터 타입과 예외

throws 키워드

  • 어떤 메서드든 throws로 예외를 호출자에게 넘길 수 있습니다
    • 메서드 내에서 처리하는 대신
    • 이를 "예외 던지기" 또는 "책임 넘기기"라고 합니다
    • 예외 처리 책임을 호출자에게 위임합니다
  • throws 뒤에 예외 타입을 콤마로 구분해 나열합니다
    • 호출 메서드가 예상할 수 있는 예외 유형을 표시합니다
public static void someMethod() throws IndexOutOfBoundsException, 
NegativeArraySizeException, NullPointerException {
  // method code
}
Java의 데이터 타입과 예외
throws 예시

일반적인 try-catch로 Exception 처리

public static void main(String[] args) {
  someMethod();
}
public static void someMethod(){
  try {
    ArrayList<String> games
      = new ArrayList<String>();
    games.add("Monopoly");
    games.add("Chess");
    games.get(3);
  } catch (IndexOutOfBoundsException e) {
    System.out.println(
   "Oops - trying to get non-existent item");
  }
}

throws로 Exception 처리

public static void main(String[] args) {
  try {
    someMethod();
  } catch (IndexOutOfBoundsException e) {
    System.out.println(
   "someMethod tried to get non-existent item");
  }
}
public static void someMethod()
      throws IndexOutOfBoundsException {
  ArrayList<String> games
    = new ArrayList<String>();
  games.add("Monopoly");
  games.add("Chess");
  games.get(3);
}
Java의 데이터 타입과 예외

throws 사용 시점

  • "책임 넘기기"(예외 던지기)는 가급적 피합니다
    • 보통은 예외가 발생한 지점에서 try/catch로 처리하는 것이 좋습니다
  • throws를 쓰는 이유:
    • 예외가 발생한 메서드가 복구 방법을 모를 수 있음
    • 처리 로직을 중앙화하여 중복 try/catch를 줄이기 위함

예외 던지기는 보통 커스텀 예외와 함께 사용됩니다

1 Photo from https://unsplash.com/@philipparosetite
Java의 데이터 타입과 예외

catch 후 재던지기

  • Exception은 "재던지기(rethrow)"할 수 있습니다
    • 호출 메서드가 try/catch 대신 throws를 선언합니다
  • main에서 재던지면 애플리케이션이 종료됩니다

예외는 호출한 메서드로 재던질 수 있습니다

Java의 데이터 타입과 예외

재던지기 예시

public class RethrowExample {
    public static void main(String[] args) {
        try {
            method1(0);
        } catch (ArithmeticException e) {
            System.out.println("Oops - tried a bad quotient");
        }
    }
    public static void method1(int divisor) throws ArithmeticException {
        method2(divisor);
    }
    public static void method2 (int divisor) throws ArithmeticException {
        int z = 5/divisor;
        System.out.println(z);
    }
}
Java의 데이터 타입과 예외

연습해 봅시다!

Java의 데이터 타입과 예외

Preparing Video For Download...