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
'💻 하나씩 차곡차곡 > Back-end' 카테고리의 다른 글
"나도 드디어...성능 최적화를...?" - 대용량 INSERT 성능 개선: SQL Session 배치 처리로 최적화하기 (0) | 2025.02.07 |
---|---|
[JPA] 데이터베이스 연결이 안된다, 콘솔창에 DDL문이 안보인다 등등 (0) | 2025.01.06 |
[스프링(Spirng)] Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured. 해결방법 (0) | 2024.12.24 |
시스템 설계 기초 (로드밸런스, 메세지 큐, CDN, DNS 등) (0) | 2024.08.12 |
[HTTP] HTTP상태코드 / HTTP헤더 (0) | 2024.08.09 |