✅ 1. Checked Exception (컴파일 시 강제 처리)
1.1 IOException 설명: 입출력 시 문제가 발생 예시:
try {
FileReader fr = new FileReader("no-file.txt");
} catch (IOException e) {
System.out.println("파일을 찾을 수 없습니다.");
}
✅ 해결: try-catch로 처리하거나 throws 선언
1.2 FileNotFoundException 설명: 파일이 존재하지 않음 (IOException 하위) 예시:
try {
FileInputStream file = new FileInputStream("missing.txt");
} catch (FileNotFoundException e) {
System.out.println("해당 파일이 없습니다.");
}
✅ 해결: 파일 경로 확인, 예외 처리
1.3 ClassNotFoundException 예시:
try {
Class.forName("com.unknown.ClassName");
} catch (ClassNotFoundException e) {
System.out.println("클래스를 찾을 수 없습니다.");
}
✅ 해결: 클래스가 존재하는지 확인
1.4 SQLException 예시:
try {
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/db", "user", "pass");
Statement stmt = conn.createStatement();
stmt.executeQuery("SELECT * FROM non_table");
} catch (SQLException e) {
System.out.println("SQL 에러: " + e.getMessage());
}
✅ 해결: SQL 문법 및 테이블 존재 여부 확인
❗ 2. Unchecked Exception (RuntimeException 하위)
2.1 NullPointerException 예시:
String str = null;
System.out.println(str.length());
✅ 해결: null 체크 필수
2.2 ArrayIndexOutOfBoundsException 예시:
int[] nums = {1, 2, 3};
System.out.println(nums[3]);
✅ 해결: 배열 길이 체크
2.3 ArithmeticException 예시:
int result = 10 / 0;
✅ 해결: 0으로 나누는지 검사
2.4 NumberFormatException 예시:
String s = "abc";
int num = Integer.parseInt(s);
✅ 해결: 숫자 포맷인지 확인
2.5 ClassCastException 예시:
Object x = new Integer(10);
String y = (String) x;
✅ 해결: instanceof 검사 후 캐스팅
🔥 3. Error (복구 불가 심각한 문제)
3.1 StackOverflowError 예시:
public static void call() {
call();
}
✅ 해결: 재귀 종료 조건 필요
3.2 OutOfMemoryError 예시:
int[] big = new int[Integer.MAX_VALUE];
✅ 해결: 데이터 구조 최적화, JVM 메모리 옵션 설정
3.3 NoClassDefFoundError
✅ 해결: classpath 확인
✅ [계속] 주요 예외들
IllegalArgumentException 예시:
if (age < 0) throw new IllegalArgumentException("음수 나이 불가");
✅ 인자 유효성 검사
IllegalStateException 예시:
Scanner sc = new Scanner(System.in);
sc.close();
sc.nextLine();
✅ 상태 확인 후 작업
IndexOutOfBoundsException 예시:
list.get(5);
✅ .size() 체크
UnsupportedOperationException 예시:
List<String> list = Arrays.asList("a", "b");
list.add("c");
✅ 불변 리스트 확인
CloneNotSupportedException 예시:
class A implements Cloneable {
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
✅ implements Cloneable 추가
InterruptedException 예시:
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// 처리
}
✅ try-catch 처리 및 interrupt 상태 체크
📚 정리된 예외/에러 목록
예외 클래스
✅ Checked Exception | IOException | Exception | 입출력 오류 발생 시 사용. 파일/네트워크 문제 등. |
✅ Checked Exception | SQLException | Exception | 데이터베이스 SQL 오류. |
✅ Checked Exception | ParseException | Exception | 문자열을 날짜 등으로 파싱 중 실패. |
✅ Checked Exception | ClassNotFoundException | Exception | 지정한 클래스가 존재하지 않음. |
✅ Checked Exception | InterruptedException | Exception | 스레드가 중단되었을 때 발생. |
✅ Checked Exception | FileNotFoundException | IOException | 특정 파일을 찾지 못할 때 발생. |
✅ Checked Exception | CloneNotSupportedException | Exception | 객체 복제가 허용되지 않았을 때 발생. |
✅ Checked Exception | InstantiationException | Exception | 클래스 인스턴스화 실패 (ex. 추상 클래스 인스턴스화). |
✅ Checked Exception | NoSuchMethodException | Exception | 존재하지 않는 메서드 접근 시. |
✅ Checked Exception | InvocationTargetException | Exception | 리플렉션으로 호출한 메서드에서 예외 발생 시. |
✅ Checked Exception | NoSuchFieldException | Exception | 존재하지 않는 필드 접근 시. |
✅ Checked Exception | MalformedURLException | Exception | 잘못된 URL 형식. |
✅ Checked Exception | URISyntaxException | Exception | 잘못된 URI 문법. |
✅ Checked Exception | BindException | IOException | 포트 충돌 등 네트워크 오류. |
✅ Checked Exception | EOFException | IOException | 파일 끝 도달. |
✅ Checked Exception | NotSerializableException | IOException | 직렬화 실패. |
✅ Checked Exception | ZipException | IOException | 압축 파일 처리 오류. |
✅ Checked Exception | BrokenBarrierException | Exception | 병렬 처리 중 동기화 실패. |
예외 클래스 (Unchecked)
⚠️ Unchecked Exception | NullPointerException | RuntimeException | 참조변수가 null인 상태에서 접근 시. |
⚠️ Unchecked Exception | ArrayIndexOutOfBoundsException | IndexOutOfBoundsException | 배열 인덱스가 범위를 벗어남. |
⚠️ Unchecked Exception | StringIndexOutOfBoundsException | IndexOutOfBoundsException | 문자열 인덱스 오류. |
⚠️ Unchecked Exception | ArithmeticException | RuntimeException | 0으로 나누기 등 수학적 오류. |
⚠️ Unchecked Exception | IllegalArgumentException | RuntimeException | 부적절한 인자 전달 시. |
⚠️ Unchecked Exception | IllegalStateException | RuntimeException | 잘못된 상태에서 메서드 호출 시. |
⚠️ Unchecked Exception | NumberFormatException | IllegalArgumentException | 문자열을 숫자로 변환 실패. |
⚠️ Unchecked Exception | ClassCastException | RuntimeException | 잘못된 형변환 시. |
⚠️ Unchecked Exception | UnsupportedOperationException | RuntimeException | 지원되지 않는 연산 수행 시. |
⚠️ Unchecked Exception | IndexOutOfBoundsException | RuntimeException | 리스트나 배열 등의 인덱스 범위 초과. |
⚠️ Unchecked Exception | NegativeArraySizeException | RuntimeException | 배열 크기를 음수로 지정할 때 발생. |
⚠️ Unchecked Exception | SecurityException | RuntimeException | 보안 위반 시 발생. |
⚠️ Unchecked Exception | MissingResourceException | RuntimeException | 리소스를 찾을 수 없을 때 발생. |
⚠️ Unchecked Exception | EmptyStackException | RuntimeException | 스택이 비어있을 때 발생. |
⚠️ Unchecked Exception | ConcurrentModificationException | RuntimeException | 컬렉션 수정 중 반복 시 발생. |
⚠️ Unchecked Exception | IllegalMonitorStateException | RuntimeException | wait/notify 오용 시 발생. |
⚠️ Unchecked Exception | EnumConstantNotPresentException | RuntimeException | 존재하지 않는 enum 상수 접근 시 발생. |
⚠️ Unchecked Exception | NoSuchElementException | RuntimeException | Iterator에서 더 이상 요소가 없을 때 발생. |
⚠️ Unchecked Exception | InputMismatchException | RuntimeException | 입력 형식이 맞지 않을 때 발생. |
⚠️ Unchecked Exception | IllegalThreadStateException | RuntimeException | 잘못된 스레드 상태 오류. |
⚠️ Unchecked Exception | AssertionError | Error | assert 실패 시 발생. |
에러 클래스
❌ Error | OutOfMemoryError | VirtualMachineError | JVM 메모리 부족. |
❌ Error | StackOverflowError | VirtualMachineError | 재귀 호출이 너무 깊어 스택 초과. |
❌ Error | VirtualMachineError | Error | JVM에 심각한 오류 발생 시. |
❌ Error | InternalError | VirtualMachineError | JVM 내부 오류. |
❌ Error | UnknownError | VirtualMachineError | 원인 불명의 치명적 오류. |
❌ Error | NoClassDefFoundError | LinkageError | JVM이 클래스 정의를 찾지 못함. |
❌ Error | UnsatisfiedLinkError | LinkageError | 네이티브 메서드가 존재하지 않음. |
❌ Error | ExceptionInInitializerError | LinkageError | static 초기화 블록에서 예외 발생. |
❌ Error | ClassFormatError | LinkageError | 잘못된 바이트코드 형식. |
❌ Error | AssertionError | Error | assert 문 실패. |
❌ Error | AbstractMethodError | IncompatibleClassChangeError | 추상 메서드가 구현되지 않았을 때 발생. |