[JAVA] 자바를 JAVA(5)

wannabeing·2025년 3월 14일
1

SPARTA-TIL

목록 보기
5/22

✅ 예외(Exception)

  • 프로그램 실행 중 예상하지 못한 상황이 발생하는 것을 의미한다.

▶️ throw - 의도적인 예외

  • 특정 조건에서 의도적으로 예외를 발생시킬 때 throw 키워드를 사용한다.

✅ 예외 구조와 종류

1️⃣ RuntimeException

  • UncheckedException 라고 한다.
  • 예외처리를 컴파일러가 확인하지 않는다. (체크하지 않는다.)
  • 비정상 종료(예외전파)

2️⃣ Exception

  • CheckedException 라고 한다.
  • 예외처리를 컴파일러가 확인한다.
  • 반드시 try-catch 혹은 throw 키워드를 사용하여 예외처리를 한다.
    책임전가: 예외를 호출한 곳에서 강제처리하도록 하는 방식이다.

💡 예외전파

  • 자식 메서드에서 발생한 예외를 부모 메서드로 전달하는 과정
  • 계속 올라가다 보면 main까지 가고, 비정상 종료된다.

✅ Optional

  • null을 안전하게 다루게 해주는 객체
  • null을 직접 다루면 NullPointerException 예외가 발생할 수 있으므로
    Optional를 사용하여 예외방지를 할 수 있다.
  • if문으로 null 처리 시, 미리 예측하고 코드를 짜야 되는데
    미리 예측하고 사용하기에 현실적으로 어렵다.
  • 따라서 Optional을 사용해야 한다!

    ❓ null이란
    값이 없음 또는 참조하지 않음을 나타낸다.

Optional은 값이 있거나 값이 없을 수 있는 형태이다.

  • isPresent() 을 이용하면 null의 여부에 따라 true/false를 반환한다.
// Optional<객체>
Optional<Student> studentOptional = camp.getStudent();

// isPresent으로 true/false 반환
boolean flag = studentOptional.isPresent();

값이 없으면 특정값을 반환하게 할 수 있다.

▶️ orElse()

/**
 * 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동작이 있는 경우,
    null이 아니어도 무조건 DB동작이 생기므로 조심하자!

▶️ orElseGet()

/**
  * 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이면 실행되지 않는다.

  • Supplier 함수형 인터페이스의 경우,
    Optional에 값이 없을 경우에만 get() 메서드를 통해 실행된다.

// ✅ 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()을 사용
  • DB작업이 포함된 메서드를 인자로 넘길 경우, orElse() 사용은 지양해야 함

✅ Collection

  • 자료구조를 쉽게 이용할 수 있게 Interface와 Class로 제공하는 집합이다.
  • 정적인 배열은 크기가 한정되지만,
    ArrayList는 배열의 길이가 고정되지 않은 객체이기 때문에
    더 많은 기능을 활용할 수 있게 된다.
인터페이스특징구현체
List순서 유지, 중복허용ArrayList
Set순서없음, 중복불가HashSet
Map키-값 구조, 키 중복불가HashMap

출처

orElse와 orElseGet 차이점을 알고 쓰자
orElse와 orElseGet 무슨 차이가 있을까
orElse vs orElseGet
스파르타코딩클럽 Java 문법 종합반 3주차

profile
wannabe---ing

0개의 댓글