Spring, Java 🌵

throws 와 throw new 차이점

MAYMIN 2024. 6. 1. 12:40
728x90
SMALL

코드를 짤 때, throws 와 throw new 를 정말 헷갈려했다.

 

이번 기회로 정확하게 이해하고 가기로 하자 ! 😃

 

1. throws 키워드

throws 키워드는 메서드 시그니처에 사용되어 해당 메서드가 특정 예외를 던질 수 있음을 명시합니다.

주로 체크드 예외(Checked Exception)를 호출자에게 전달하고 싶을 때 사용

import java.io.IOException;

public class ThrowsExample {

    public static void main(String[] args) {
        ThrowsExample example = new ThrowsExample();
        try {
            example.readFile();
        } catch (IOException e) {
            System.out.println("예외 발생: " + e.getMessage());
        }
    }

    public void readFile() throws IOException {
        // 파일을 읽는 코드
        throw new IOException("파일을 읽을 수 없습니다.");
    }
}

여기서는 readFile 메서드가 IOException을 던질 수 있음을 명시하고, 호출하는 쪽에서 이 예외를 처리하도록 강제한다.

 

-> example.readFile(); 을 호출하면, readFile에는 throws IOException을 던지고있다.

이때, 해당 익셉션이 발생하면, readFile을 호출한 곳에서 예외를 처리시켜줘야한다.

즉, throws 는 내가 처리안해! 나를 호출한 너가 에러 처리해줘 ~

 

2. throw new 키워드

throw new는 특정 조건이 발생했을 때 직접 예외를 던질 때 사용

주로 메서드 내부에서 특정 상황이 발생하면 예외를 명시적으로 발생시킬 때 사용

public class ThrowNewExample {

    public static void main(String[] args) {
        ThrowNewExample example = new ThrowNewExample();
        try {
            example.checkAge(15);
        } catch (IllegalArgumentException e) {
            System.out.println("예외 발생: " + e.getMessage());
        }
    }

    public void checkAge(int age) {
        if (age < 18) {
            throw new IllegalArgumentException("나이는 18세 이상이어야 합니다.");
        }
    }
}

여기서는 checkAge 메서드에서 나이가 18세 미만일 때 IllegalArgumentException을 던진다.

-> checkAge 에서 에러가 발생하면, 직접 에러를 던져서 처리한다.

 

 

throws:

  • 위치: 메서드 시그니처
  • 목적: 메서드가 특정 예외를 던질 수 있음을 선언
  • 예제: public void myMethod() throws IOException { }

 

throw new:

  • 위치: 메서드 내부
  • 목적: 명시적으로 예외를 발생
  • 예제: throw new IOException("파일을 읽을 수 없습니다.");

 

 

728x90
LIST