throw 키워드를 사용한다.
UncheckedException 라고 한다.CheckedException 라고 한다.try-catch 혹은 throw 키워드를 사용하여 예외처리를 한다.💡 예외전파
- 자식 메서드에서 발생한 예외를 부모 메서드로 전달하는 과정
- 계속 올라가다 보면
main까지 가고, 비정상 종료된다.
NullPointerException 예외가 발생할 수 있으므로Optional를 사용하여 예외방지를 할 수 있다.Optional을 사용해야 한다!❓ null이란
값이 없음또는참조하지 않음을 나타낸다.
Optional은 값이 있거나 값이 없을 수 있는 형태이다.isPresent() 을 이용하면 null의 여부에 따라 true/false를 반환한다.// Optional<객체>
Optional<Student> studentOptional = camp.getStudent();
// isPresent으로 true/false 반환
boolean flag = studentOptional.isPresent();
/**
* Return the value if present, otherwise return {@code other}.
*
* @param other the value to be returned
* if there is no value present, may be null
* @return the value, if present, otherwise {@code other}
*/
public T orElse(T other) {
return value != null ? value : other;
}
orElse()는 해당 값이 있거나 없거나 항상 호출된다.T otehr에 메소드가 들어가면, 항상 호출된다.// ✅ orElse 예시
Coupon newCoupon = new Coupon("newCoupon");
Coupon elseCoupon = Optional.of(newCoupon)
.orElse(getNullCoupon());
System.out.println(elseCoupon);
private Coupon getNullCoupon() {
System.out.println("널 쿠폰입니다.");
return new Coupon("nullCoupon");
}
// ✅ orElse 출력예시
널 쿠폰입니다.
Coupon{value='newCoupon'}
newCoupon이지만,getNullCoupon() 메서드가 실행됐다.orElse에 넘겨준 메서드의 DB동작이 있는 경우,/**
* Return the value if present,
* otherwise invoke {@code other} and return
* the result of that invocation.
*
* @param other a {@code Supplier}
* whose result is returned if no value is present
* @return the value if present otherwise the result of
* {@code other.get()}
* @throws NullPointerException if value is not present
* and {@code other} is null
*/
public T orElseGet(Supplier<? extends T> other) {
return value != null ? value : other.get();
}
orElseGet()는 해당 값이 없을 때만 호출된다.other를 바로 실행하는 것이 아니라,other.get()을 실행하기 때문에 null이면 실행되지 않는다.// ✅ orElseGet 예시
Coupon newCoupon = new Coupon("newCoupon");
Coupon elseGetCoupon = Optional.of(newCoupon)
.orElseGet(this::getNullCoupon);
System.out.println(elseGetCoupon);
private Coupon getNullCoupon() {
System.out.println("널 쿠폰입니다.");
return new Coupon("nullCoupon");
}
// ✅ orElseGet 출력예시
Coupon{value='newCoupon'}
orElseGet() 은 우리가 예상한대로 null이 아닐경우에는getNullCoupon() 메서드가 실행되지 않았다.상황에 맞게 사용하면 좋을 것 같다.
orElseGet()을 사용orElse() 사용은 지양해야 함
| 인터페이스 | 특징 | 구현체 |
|---|---|---|
List | 순서 유지, 중복허용 | ArrayList |
Set | 순서없음, 중복불가 | HashSet |
Map | 키-값 구조, 키 중복불가 | HashMap |
orElse와 orElseGet 차이점을 알고 쓰자
orElse와 orElseGet 무슨 차이가 있을까
orElse vs orElseGet
스파르타코딩클럽 Java 문법 종합반 3주차