Java에서 예외(Exception)는 크게 두 가지로 나뉩니다:
- Checked Exception (검사 예외)
- Unchecked Exception (비검사 예외, RuntimeException 계열)
아래에 각 종류별로 대표적인 예시 입니다.
1. Checked Exception (컴파일 타임에 반드시 처리해야 하는 예외)
예외 클래스 설명
IOException | 입출력 중 발생하는 예외 (파일, 스트림 등) |
SQLException | DB 작업 중 발생하는 예외 |
FileNotFoundException | 파일을 찾을 수 없을 때 |
ClassNotFoundException | 클래스를 로딩할 수 없을 때 |
InterruptedException | 스레드가 대기 상태에서 인터럽트될 때 |
ParseException | 날짜 등 문자열 파싱 중 오류 발생 |
예시 코드 (Checked Exception):
public void readFile(String path) throws IOException {
BufferedReader reader = new BufferedReader(new FileReader(path));
String line = reader.readLine();
reader.close();
}
2. Unchecked Exception (RuntimeException과 그 하위 클래스)
예외 클래스 설명
NullPointerException | null 객체를 참조할 때 |
ArrayIndexOutOfBoundsException | 배열 인덱스 범위 초과 |
IllegalArgumentException | 잘못된 인자 전달 |
ArithmeticException | 0으로 나누기 등 산술적 오류 |
ClassCastException | 잘못된 형변환 |
NumberFormatException | 문자열을 숫자로 파싱할 수 없을 때 |
예시 코드 (Unchecked Exception):
public int divide(int a, int b) {
return a / b; // b가 0이면 ArithmeticException 발생
}
Custom Exception (사용자 정의 예외)
public class InsufficientBalanceException extends Exception {
public InsufficientBalanceException(String message) {
super(message);
}
}
사용 시:
if (balance < amount) {
throw new InsufficientBalanceException("잔액 부족");
}
아래는 자주 사용되는 Java 예외들에 대해 예외 처리 방식과 메시지 출력 방법을 예시 코드와 함께 정리한 것입니다.
1. IOException (입출력 오류)
처리 방식: try-catch로 감싸고 메시지 출력
try {
BufferedReader reader = new BufferedReader(new FileReader("file.txt"));
String line = reader.readLine();
reader.close();
} catch (IOException e) {
System.out.println("입출력 오류: " + e.getMessage());
e.printStackTrace(); // 상세 오류 출력
}
2. FileNotFoundException (파일 없음)
try {
FileInputStream fis = new FileInputStream("not_exist.txt");
} catch (FileNotFoundException e) {
System.out.println("파일을 찾을 수 없습니다: " + e.getMessage());
}
3. SQLException (DB 관련 오류)
try {
Connection conn = DriverManager.getConnection(...);
Statement stmt = conn.createStatement();
stmt.executeQuery("SELECT * FROM table");
} catch (SQLException e) {
System.out.println("데이터베이스 오류: " + e.getMessage());
}
4. NullPointerException (null 참조)
try {
String str = null;
System.out.println(str.length()); // 여기서 NPE 발생
} catch (NullPointerException e) {
System.out.println("Null 참조 오류: " + e.getMessage());
}
5. ArithmeticException (0으로 나누기)
try {
int result = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("산술 오류: " + e.getMessage()); // "/ by zero"
}
6. ArrayIndexOutOfBoundsException (배열 인덱스 초과)
try {
int[] arr = {1, 2, 3};
System.out.println(arr[5]);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("배열 인덱스 오류: " + e.getMessage());
}
7. NumberFormatException (문자열 숫자 변환 실패)
try {
int num = Integer.parseInt("abc"); // 숫자로 변환 불가
} catch (NumberFormatException e) {
System.out.println("숫자 형식 오류: " + e.getMessage());
}
8. 사용자 정의 예외
public class CustomException extends Exception {
public CustomException(String message) {
super(message);
}
}
// 사용
try {
throw new CustomException("사용자 정의 예외 발생");
} catch (CustomException e) {
System.out.println("커스텀 예외: " + e.getMessage());
}
예외 메시지 출력 방법 요약
- e.getMessage() → 간단한 메시지
- e.printStackTrace() → 예외 발생 위치 포함 전체 스택 추적 출력t
- Logger를 사용해 로그로 남길 수도 있음 (실무 권장)
'[JAVA]JAVA실무' 카테고리의 다른 글
[JAVA]System.out.println VS Logger (1) | 2025.04.22 |
---|---|
[JAVA]실무 try-catch exception 처리 (0) | 2025.04.21 |
[JAVA]Spring 기반 웹 애플리케이션 기본 구조 (0) | 2025.04.14 |
[JAVA]보안취약점 조치 예시(기초) PMD (0) | 2025.03.22 |
[JAVA]보안취약점 분석 PMD 사용방법 (0) | 2025.03.22 |