아래의 내용은 java_grammer 레파지토리 C07ExceptionFileParsing 디렉터리에 저장되어있는 내용을 정리함
- C01ExceptionBasic
- C02ExceptionAdvance
예외처리 기본 → throw/throws → 실전 패턴 워크플로우
| 구분 | 에러(Error) | 예외(Exception) |
|---|---|---|
| 발생원인 | 시스템 장애(스택오버플로우, 메모리 부족) | 코드 로직 오류(사용자입력, 파일읽기, 네트워크) |
| 대처 | 대비 코드 작성 X | try/catch 필수 |
| 예시 | java.lang.Error | ArithmeticException, IOException |
예외처리 목적
1. 사용자에게 적절한 에러 메시지 전달 (가장 중요)
2. logging/debugging
3. 프로그램 강제종료 방지 (오히려 일부러 발생시키는게 더 중요)
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 작성
static boolean register(String email, String password) {
if (password.length() < 10) {
throw new IllegalArgumentException("비밀번호가 너무 짧습니다.");
}
System.out.println("DB 저장(가정)");
return true;
}
사용이유: 트랜잭션 롤백, 사용자 메시지 전달, 코드 강제 중지
static String fileRead(String path) throws IOException {
return Files.readString(Paths.get(path));
}
Checked Exception만: IOException, SQLException 등 외부시스템 관련
| 구분 | Checked Exception | Unchecked Exception (RuntimeException) |
|---|---|---|
| 컴파일시 확인 | O (throws 필수) | X |
| 예시 | IOException, SQLException | ArithmeticException, 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); // 롤백 유발
}
}
| 예외클래스 | 발생상황 | 예방법 |
|---|---|---|
ArithmeticException | 0으로 나누기 | if (tail != 0) |
NumberFormatException | "abc" → Integer.parseInt() | try/catch |
NullPointerException | null 객체 메서드 호출 | 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 IOException → RuntimeException 변환throw → Controller에서 사용자 메시지예외 메시지 문구가 REST API 상태코드+logging의 핵심.