【 개발 이야기 】

Throwable & Exception

홍호나 2025. 3. 26. 10:43

Throwable

The base class for all errors and exceptions. Only instances of this class can be thrown or caught.
매개변수
- message : the detail message string.
- cause : the cause of this throwable.

 

Exception

The class Exception and its subclasses are a form of Throwable that indicates conditions that a reasonable application might want to catch. The class Exception and any subclasses that are not also subclasses of RuntimeException are checked exceptions. Checked exceptions need to be declared in a method or constructor's throws clause if they can be thrown by the execution of the method or constructor and propagate outside the method or constructor boundary.

Exception Class와 하위 클래스는 애플리케이션이 캐치하고자하는 상태를 지칭하는 Throwable의 한 형태이다.
RuntimeException의 하위 클래스가 아닌 Exception들은 모두 checked exception이다.
checked exception은 메소드나 생성자의 throws 구절에 정의되어야한다.

  체크 예외 (Checked Exception) 런타임 예외 (Unchecked Exception)
상속 관계 Exception(단, RuntimeException 제외) RuntimeException 상속
예시 IOException, SQLException NullPointerException, IllegalArgumentException
throws 필요 여부 필요 불필요
목적 예상 가능한 예외, 반드시 처리해야 함 프로그래머 실수로 발생하는 예외

Exception

Throwable을 상속받으며, try-catch 문을 사용해 잡을 수 있다.

예외가 발생할 가능성이 있는 메서드(빨간 밑줄 그어지는 그것들!) 에서는 반드시 throws를 해줘야 한다.

예로는 IOException 같은 예외가 있다.

@Throws(IOException::class)
fun readFile(file: String): String {
    // 파일 읽기 로직 (IOException 발생 가능)
}

이렇게 throws를 하게 되면 컴파일러가 예외 처리를 강제한다.