Java throw vs throws: 예외 처리 실전 예제로 마스터하기
Java throw vs throws: 실전 예제로 예외 처리 마스터하기
이 가이드는 Java throw와 throws 키워드를 효과적 예외 처리에 사용하는 법을 실전 코드 샘플로 설명합니다.
Java에서 예외는 두 범주로 나뉩니다:
- 언체크드 예외 – 컴파일 타임 아닌 런타임에 검증. 예:
ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException, 모든 Error 하위 클래스.
- 체크드 예외 – 컴파일러 강제. 예:
IOException, InterruptedException 등.
더 깊은 다이브는 Java Exceptions 참조.
언체크드 예외는 보통 프로그래밍 실수 신호; 잡기보다 수정 권장. 체크드 예외는 호출자가 인지하고 처리해야 할 조건 표현.
throws 키워드 사용
throws 절은 메서드가 하나 이상 예외 던질 수 있음 선언, 책임 호출자에게 위임. 문법:
accessModifier returnType methodName() throws ExceptionType1, ExceptionType2 { /* 코드 */ }
여러 예외 타입 콤마로 구분 나열 가능.
예제 1: 체크드 예외 선언
import java.io.*; class Main { public static void findFile() throws IOException { // IOException 유발 가능 코드 File newFile = new File("test.txt"); FileInputStream stream = new FileInputStream(newFile); } public static void main(String[] args) { try { findFile(); } catch (IOException e) { System.out.println(e); } } }
출력
java.io.FileNotFoundException: test.txt (No such file or directory)
test.txt 없으면 FileInputStream이 FileNotFoundException 던짐(IOException 하위 클래스). findFile()이 throws IOException 선언했으므로 main() 메서드 처리 또는 전파 필수.
여러 예외 던지기
단일 throws 절에 여러 예외 타입 선언 가능:
import java.io.*; class Main { public static void findFile() throws NullPointerException, IOException, InvalidClassException { // 잠재적 NullPointerException … // 잠재적 IOException … // 잠재적 InvalidClassException … } public static void main(String[] args) { try { findFile(); } catch (IOException e1) { System.out.println(e1.getMessage()); } catch (InvalidClassException e2) { System.out.println(e2.getMessage()); } } }
NullPointerException은 언체크드라 호출자가 잡거나 선언 불필요.
throws vs try...catch 사용 시기
예외 던질 수 있는 모든 메서드에 try...catch 임베딩 시 코드 지저분해지고 로직 불명확. throws 선언으로 메서드 시그니처 깔끔 유지, 상위 레벨 코드가 에러 처리 방식 결정.
throw 키워드 사용
throw 문은 예외 인스턴스 명시적 던지기, 제어 가장 가까운 일치 catch 블록 또는 미처리 시 프로그램 종료로 전이.
문법:
throw throwableObject;
여기서 throwableObject는 Throwable 또는 하위 클래스 인스턴스.
예제 2: 언체크드 예외 던지기
class Main { public static void divideByZero() { throw new ArithmeticException("Trying to divide by 0"); } public static void main(String[] args) { divideByZero(); } }
출력
Exception in thread "main" java.lang.ArithmeticException: Trying to divide by 0 at Main.divideByZero(Main.java:3) at Main.main(Main.java:7) exit status 1
ArithmeticException 언체크드라 잡기 선택사항.
예제 3: 체크드 예외 던지기
import java.io.*; class Main { public static void findFile() throws IOException { throw new IOException("File not found"); } public static void main(String[] args) { try { findFile(); System.out.println("Rest of code in try block"); } catch (IOException e) { System.out.println(e.getMessage()); } } }
출력
File not found
여기서 findFile()이 체크드 IOException 던지므로 호출자 처리 또는 선언 필수. main() 메서드 예외 잡아 프로그램 종료 방지 시연.