예외 처리 전략

TIL·2023년 1월 8일
0

Java (최은빈)

목록 보기
26/27

복구

  • 네트워크 불안정으로 인한 DB 접속 불가로 SQLException 발생하는 경우, 비번 여러번 틀리는 경우
    • 일정 시간 대기 후 재시도
    • 정해진 횟수 초과하면 예외 복구 포기
int MAX_RETRY = 5;
while(maxRetry > MAX_RETRY) { // 기회 횟수 제한
    try {

    } catch () {

    } finally {

    }
    maxRetry--; // 기회 횟수 제한
}
throw new RetryFailedException(); // 최대 재시도 횟수 이후 직접 예외 발생



회피

public void add() throws SQLException { // 호출부(상위)로 전달
    // JDBC API
}

public void add() throws SQLException {
    try {
        // JDBC API
    } catch (SQLException e) {
        // 로그만 출력하고 전달
        throw e;
    }
}



**전환**

  • 많이 사용함
  • 런타임 예외 보편화 : checked -> unchecked(복구 가능한 예외) 추세 (wrapping)
public void add(User user) throws DuplicateUserIdException, SQLException {
    try {
        // user를 DB 등록
    } catch (SQLException e) { // SQLException 발생하면 
        if (e.getErrorCode() == MysqlErrorNumbers.ER_DUP_ENTRY) {
            throw DuplicateUserIdErrorException(); // DuplicateUserIdErrorException 로 바꿔서 (ID 중복)
        } else {
            throw e; // 전달
        }
    }
}
// NumberFormatException -> InputMismatchException
public int nextInt(int radix) {
        if ((typeCache != null) && (typeCache instanceof Integer)
            && this.radix == radix) {
            int val = ((Integer)typeCache).intValue();
            useTypeCache();
            return val;
        }
        setRadix(radix);
        clearCaches();
        try {
            String s = next(integerPattern());
            if (matcher.group(SIMPLE_GROUP_INDEX) == null)
                s = processIntegerToken(s);
            return Integer.parseInt(s, radix);
        } catch (NumberFormatException nfe) {
            position = matcher.start();
            throw new InputMismatchException(nfe.getMessage());
        }
    }



**rollback**

  • checked exception : not rollback
    • 디비에서 일어난 추가/수정/삭제 도중 예외 발생 시 취소 불가
    • 개발자가 예외 핸들링 했다고 믿음
  • unchecked exception : rollback
    • => 스프링의 기본 전략은 맞지만 개발자가 수정이 가능한 영역
      @Transactional(rollbackFor=””, noRollBackFor())

0개의 댓글

관련 채용 정보