[Java] 심화 - 예외처리(Exception)

이지연·2025년 12월 25일

개요

아래의 내용은 java_grammer 레파지토리 C07ExceptionFileParsing 디렉터리에 저장되어있는 내용을 정리함


에러 vs 예외 구분

구분에러(Error)예외(Exception)
발생원인시스템 장애(스택오버플로우, 메모리 부족)코드 로직 오류(사용자입력, 파일읽기, 네트워크)
대처대비 코드 작성 Xtry/catch 필수
예시java.lang.ErrorArithmeticException, IOException

예외처리 목적
1. 사용자에게 적절한 에러 메시지 전달 (가장 중요)
2. logging/debugging
3. 프로그램 강제종료 방지 (오히려 일부러 발생시키는게 더 중요)


기본 문법 - try/catch/finally

예외처리 전 (문제 코드)

int head = Integer.parseInt(sc.nextLine());
int tail = Integer.parseInt(sc.nextLine());
int result = head / tail; // ArithmeticException: / by zero

문제: 1) 코드 중단 2) 사용자 메시지 X 3) 로그 X

예외처리 후

try {
    int head = Integer.parseInt(sc.nextLine());
    int tail = Integer.parseInt(sc.nextLine());
    int result = head / tail;
    System.out.println("결과: " + result);
} catch (ArithmeticException e) {
    System.out.println("0으로 나누면 안됩니다.");
    e.printStackTrace(); // 디버깅 로그
} catch (NumberFormatException e) {
    System.out.println("문자를 입력하면 안됩니다.");
    e.printStackTrace();
} catch (Exception e) { // 모든 예외의 조상
    System.out.println("예상치 못한 에러");
    e.printStackTrace();
} finally {
    System.out.println("무조건 실행"); // 자원 정리용
}

중요: 구체적인 예외 → Exception 순으로 catch 작성


throw vs throws

throw - 의도적 예외 발생

static boolean register(String email, String password) {
    if (password.length() < 10) {
        throw new IllegalArgumentException("비밀번호가 너무 짧습니다.");
    }
    System.out.println("DB 저장(가정)");
    return true;
}

사용이유: 트랜잭션 롤백, 사용자 메시지 전달, 코드 강제 중지

throws - 예외 위임

static String fileRead(String path) throws IOException {
    return Files.readString(Paths.get(path));
}

Checked Exception만: IOException, SQLException 등 외부시스템 관련


Checked vs Unchecked

구분Checked ExceptionUnchecked Exception (RuntimeException)
컴파일시 확인O (throws 필수)X
예시IOException, SQLExceptionArithmeticException, NullPointerException
Spring 롤백X (try/catch 후 RuntimeException 발생 필요)O

실전 패턴 - Checked → Unchecked 변환

static String fileRead(String path) {
    try {
        return Files.readString(Paths.get(path));
    } catch (IOException e) {
        throw new RuntimeException(e); // 롤백 유발
    }
}

주요 예외 클래스들

예외클래스발생상황예방법
ArithmeticException0으로 나누기if (tail != 0)
NumberFormatException"abc" → Integer.parseInt()try/catch
NullPointerExceptionnull 객체 메서드 호출null 체크
IllegalArgumentException부적합 인자입력 검증
IndexOutOfBoundsException배열 인덱스 오류범위 체크

회원가입 시뮬레이션 (실전)

try {
    register(email, password);
} catch (IllegalArgumentException e) {
    System.out.println("회원가입 실패: " + e.getMessage());
    return; // 이후 코드 차단
}

핵심: throw로 비즈니스 규칙 위반시 즉시 중단 → DB 저장 방지


정리

  • 기본: try/catch/finally로 예상 오류 처리
  • 의도적 중단: throw new IllegalArgumentException()
  • 외부시스템: throws IOExceptionRuntimeException 변환
  • 실무: Service에서 throw → Controller에서 사용자 메시지

예외 메시지 문구가 REST API 상태코드+logging의 핵심.

profile
Eazy하게

0개의 댓글