Checked Exception 과 Unchecked Exception

kmb·2023년 5월 18일
0

자바

목록 보기
31/31
post-thumbnail

자바에서 예외(Exception)는 2가지 유형으로 분리된다.

  1. Checked Exception
  2. Unchecked Exception
Checked ExceptionUnchecked Exception
예외 확인 시점컴파일 시점(Compile)런타임 시점(Runtime)
처리 여부반드시 예외 처리 (try-catch 또는 throws로)명시적으로 하지 않아도 무관
Spring Framework에서의 Transaction 처리예외 발생 시 Rollback 수행 X예외 발생 시 Rollback 수행 O
예시IOException, SQLException,NullPointerException, IllegalArgumentException, IndexOutOfBoundException

⚠️주의할 점은 위 정책은 Spring AOP 기반의 @Transactional에서만 적용되는 기본 동작이고 모든 트랜잭션 처리 방식에서 동일하게 적용되는 것은 아니다.

또한 스프링에서는 @Transactional의 rollbackFor, noRollbackFor 옵션을 통해서 예외별로 롤백을 할지말지에 대한 여부를 자유롭게 설정할 수 있다.
(즉, Checked Exception도 롤백할 수 있고, Unchecked Exception도 롤백하지 않게 설정할 수 있다)


Unchecked Exception

Exception 클래스를 상속받는 Runtime Exception 클래스와 그 하위 클래스를 포함한 예외 클래스를 의미.
명시적으로 예외처리를 하지 않아도 되며, Runtime 시점에서 예외발생이 확인된다.

주로 배열의 인덱스 초과, Null Pointer 참조, Casting 오류 등과 관련된 오류를 나타낸다.

 

  • Runtime Exception 예시
public class CustomRuntimeExceptionExample {
    public static void main(String[] args) {
        try {
            calculate(10, 0);
        } catch (CustomRuntimeException e) {
            System.out.println("Error : " + e.getMessage());
        }
    }

    public static int calculate(int dividend, int divisor) {
        if (divisor == 0) {
            throw new CustomRuntimeException("Divisor는 0이 될 수 없습니다.");
        }

        return dividend / divisor;
    }
}

class CustomRuntimeException extends RuntimeException {
    public CustomRuntimeException(String message) {
        super(message);
    }
}


// 실행결과
Error : Divisor0이 될 수 없습니다.

Checked Exception

Exception 클래스를 상속받는 예외 클래스중 Runtime Exception 클래스와 그 하위 클래스들을 제외한 모든 예외 클래스를 의미.
반드시 예외처리를 해야한다. 따라서 컴파일 시점에서 예외발생이 확인된다.

주로 외부 리소스와의 상호 작용, 네트워크 통신, 파일 입출력 등과 관련된 오류를 나타낸다.

 

  • Checked Exception 중 IOException 예시
import java.io.IOException;

public class CustomIOExceptionExample {
    public static void main(String[] args) {
        try {
            readFile("테스트파일.txt");
        } catch (CustomIOException e) {
            System.out.println("Error: " + e.getMessage());
        }
    }

    public static void readFile(String filename) throws CustomIOException {
        if (!fileExists(filename)) {
            throw new CustomIOException("File not found : " + filename);
        }

        // 파일을 읽는 로직 등의 작업 수행
        System.out.println("Reading file : " + filename);
    }

    public static boolean fileExists(String filename) {
        // 파일의 존재 여부를 확인하는 로직
        return false;  // 파일이 존재하지 않는다고 가정
    }
}

class CustomIOException extends IOException {
    public CustomIOException(String message) {
        super(message);
    }
}


// 실행결과
Error: File not found : 테스트파일.txt

 

출처

profile
꾸준하게

0개의 댓글

Powered by GraphCDN, the GraphQL CDN