표준 라이브러리의 예외를 사용하면 다음과 같은 이점이 있다:
메서드 파라미터 유효성 검증에 사용
fun createUser(request: SignUpRequest) {
if (request.password.length < 8) {
throw IllegalArgumentException("비밀번호는 8자 이상이어야 합니다")
}
}
객체의 상태 검증에 사용
fun refundOrder(orderId: Long) {
if (order.status != OrderStatus.COMPLETED) {
throw IllegalStateException("완료된 주문만 환불이 가능합니다")
}
}
배열이나 컬렉션의 잘못된 인덱스 접근
@Service
class CommentService {
fun changeComment(postId: Long, commentIndex: Int, content: String) {
val comments = commentRepository.findByPostId(postId)
if (commentIndex !in comments.indices) {
throw IndexOutOfBoundsException("댓글 인덱스가 범위를 벗어났습니다 (인덱스: $commentIndex, 크기: ${comments.size})")
}
comments[commentIndex].content = content
}
}
@Service
class StockService {
fun decrease(itemId: Long, quantity: Int) {
if (!stockLock.tryLock()) {
throw ConcurrentModificationException("재고 수정 중입니다")
}
// ... 재고 감소 처리
}
}