Java에서 예외는 프로그램 실행 중 발생하는 비정상적인 상황을 의미합니다. 이 문서에서는 Java의 예외 개념, 분류 및 처리 방법에 대해 설명합니다.
예외의 개념과 구조
1.1 예외의 개념
Java에서 예외는 프로그램 실행 중 발생하는 비정상적인 행동을 나타냅니다.1.2 예외의 구조
예외 계층 구조에서Throwable은 최상위 클래스이며, 두 가지 주요 하위 클래스인 Error와 Exception으로 나뉩니다.
- Error: JVM이 해결할 수 없는 심각한 문제를 나타냅니다 (예: 메모리 부족, 스택 오버플로).
- Exception: 코드로 처리할 수 있는 예외로, 프로그램 실행을 계속할 수 있게 합니다.
1.3 예외의 분류
1.3.1 컴파일 시 예외
컴파일 단계에서 발생하는 예외로, 체크 예외라고도 불립니다.
public class User {
private String username;
private int age;
@Override
protected Object clone() {
return super.clone();
}
}
1.3.2 런타임 예외
프로그램 실행 중 발생하는 예외로, 언체크 예외입니다. 예:NullPointerException, ArrayIndexOutOfBoundsException.
예외 처리
Java에서 예외 처리는throw, throws, try-catch, finally 키워드를 사용합니다.
2.1 예외 발생
throw 키워드를 사용하여 예외를 발생시킵니다.
public class Test {
public static void check(int num) {
if(num == 0) {
throw new IllegalArgumentException("Invalid number");
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int num = sc.nextInt();
check(num);
}
}
2.2 예외 캡처
예외 캡처는throws와 try-catch를 통해 수행됩니다.
2.2.1 throws 선언
public class User {
private String username;
private int age;
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
2.2.2 try-catch 문
public class Main {
public static void process(int value) {
if(value == 0) {
throw new IllegalArgumentException();
}
}
public static void execute() {
try {
process(0);
} catch(IllegalArgumentException e) {
System.out.println("IllegalArgumentException caught");
e.printStackTrace();
} catch(ArrayIndexOutOfBoundsException e) {
System.out.println("ArrayIndexOutOfBoundsException caught");
e.printStackTrace();
}
System.out.println("After exception handling");
}
public static void main(String[] args) {
execute();
}
}
2.2.3 finally 블록
public static void resourceManagement() {
try {
int[] arr = {1, 2, 3};
System.out.println(arr[3]);
} catch(Exception e) {
System.out.println("Caught Exception");
} finally {
System.out.println("Finally block executed");
}
System.out.println("After try-catch-finally");
}
public static void main(String[] args) {
resourceManagement();
}
사용자 정의 예외
사용자 정의 예외는 일반적으로Exception 또는 RuntimeException을 상속받아 생성됩니다.
class UsernameException extends Exception {
public UsernameException(String msg) {
super(msg);
}
}
class PasswordException extends Exception {
public PasswordException(String msg) {
super(msg);
}
}
public class Auth {
private String username = "admin";
private String password = "pwd123";
public void authenticate(String user, String pass) throws UsernameException, PasswordException {
if(!username.equals(user)) {
throw new UsernameException("Wrong username");
}
if(!password.equals(pass)) {
throw new PasswordException("Incorrect password");
}
System.out.println("Login successful");
}
public static void main(String[] args) {
Auth auth = new Auth();
try {
auth.authenticate("user", "pass123");
} catch(UsernameException | PasswordException e) {
e.printStackTrace();
}
}
}