[Java] orElseThrow로 코드 가독성을 향상시키자

chiyongs·2022년 6월 24일
post-thumbnail

orElseThrow

프로젝트를 진행하면서 Optional 객체의 유무를 판단하고 예외를 처리하기 위해 if문을 사용해왔습니다.
if문을 사용하면서 예외 처리 또는 값을 반환하다보니 코드의 가독성이 떨어졌습니다.
orElseThrow를 통해 Optional에서 원하는 객체를 바로 얻거나 예외를 던질 수 있습니다.

예시 코드

public class ItemService {
	/** if문으로 처리하다보니 코드가 길어지고 반복된 작업을 해야한다는 불편함이 존재 **/
    // 예외 대신 null을 반환
    Item findItemById_if(Long itemId) {
    	Optional<Item> item = itemRepository.findById(itemId);
        if(item.isPresent()) {
        	...
            return item.get();
        }
    	return null;
    }
    
    // 예외 던짐
    Item findItemById_if2(Long itemId) {
    	Optional<Item> item = itemRepository.findById(itemId);
        if(item.isEmpty()) {
        	throw new NoSuchElementException();
        }
    	return item.get();
    }
   
   	// orElseThrow를 사용하여 코드 가독성 향상!!
    // 해당 item이 없다면 예외, 있다면 return -> 가독성 향상
    Item findItemById_orElseThrow(Long itemId) {
    	return itemRepository.findById(itemId)
        				.orElseThrow(() -> new NoSuchElementException());
    }
}


Ref

6개의 댓글

comment-user-thumbnail
2024년 12월 23일

현재 프로젝트의 일부로 if 문을 사용하여 Optional 객체가 있는지 확인하고 예외를 처리하고 있습니다.
https://velog.io/@chiyongs/orElseThrow Monkey Mart

답글 달기
comment-user-thumbnail
2025년 5월 20일

Are you a game lover? And wants to play your all favorites game with these all-exciting features which are missing in the official game. https://capcutpro.com.pk/

답글 달기
comment-user-thumbnail
2025년 5월 20일

orElseThrow는 Java에서 Optional 객체를 처리할 때 매우 유용하게 사용되는 메서드입니다. 이를 적절히 사용하면 코드의 가독성과 안정성을 크게 향상시킬 수 있습니다. https://capcutapk.com.pk/

답글 달기
comment-user-thumbnail
2025년 7월 22일

Lost Life apk is a game in which you can enjoy all the features without any restrictions and get unlimited hearts, coins and more features for free.

https://lostlifeapp.net/

답글 달기
comment-user-thumbnail
2025년 9월 13일

TeaTV APK is a free streaming app that lets users watch movies and TV shows in high quality, offering smooth performance and an easy-to-use interface

답글 달기
comment-user-thumbnail
2025년 11월 16일

orElseThrow()는 Optional 값이 없을 때 예외를 던지는 메서드로, 기존 null 체크보다 가독성이 뛰어나다. if (obj == null) 같은 조건문을 줄이고 “값이 없으면 바로 예외 발생”이라는 의도를 명확히 표현한다. 코드가 짧아지고 유지보수가 쉬워지며, 불필요한 NullPointerException 위험도 줄어든다. 특히 반드시 값이 존재해야 하는 상황이나 Stream 체인 안에서 유용하게 사용된다. 결과적으로 더 깔끔하고 안전한 코드를 작성할 수 있다.
https://ibommaapp.org/

답글 달기