본문 바로가기
💻 하나씩 차곡차곡/Back-end

[Java] IllegalArgumentException VS IllegalStateException : 어떨 때 뭘 써야 하지?

by 뚜루리 2025. 1. 17.
728x90
320x100
개발할 때 IllegalArgumentException과 IllegalStateException를 자연스럽게 많이 쓰는 경우를 봤는데 어떨 때 어떤 걸 써야 할지 알아두고 싶어서 정리!

 

 

1. IllegalArgumentException

  • 목적 : 메서드에 전달된 인자가 잘못되었을 때 사용
  • 상황
    • 값의 유효성 검사 실패 : 인자가 범위를 벗어나거나 형식이 잘못된 경우.
    • 값이 특정 제약 조건을 만족하지 않는 경우 (ex.null 값 전달 금지)
  • 사용 예시:
     
public void setAge(int age) {
    if (age < 0 || age > 150) {
        throw new IllegalArgumentException("Age must be between 0 and 150.");
    }
    this.age = age;
}

 

public void setName(String name) {
    if (name == null) {
        throw new IllegalArgumentException("Name cannot be null.");
    }
    this.name = name;
}
 
 

 

2. IllegalStateException

  • 목적: 메서드를 호출하려 했지만, 객체의 상태가 메서드 호출을 허용하지 않을 때 사용
  • 상황:
    • 객체가 적절한 상태로 초기화되지 않은 경우.
    • 메서드 호출 시 객체의 현재 상태가 그 메서드를 수행하기에 부적합한 경우.
  • 사용 예시:
public void start() {
    if (isRunning) {
        throw new IllegalStateException("The service is already running.");
    }
    isRunning = true;
}
public void stop() {
    if (!isRunning) {
        throw new IllegalStateException("Cannot stop a service that is not running.");
    }
    isRunning = false;
}
public void performAction() {
    if (!initialized) {
        throw new IllegalStateException("Object must be initialized before performing actions.");
    }
}

 


비교 요약

728x90
320x100