Checked Exception vs Unchecked Exception

yoon·2022년 9월 26일
0

Error

java.lang.Throwable class 의 subclass.
심각한 오류를 발생시키며 try-catch blcok 과 같은 어떠한 기술로도 처리할 수 없는 상태를 말한다.
unchecked type 이며 compile time 에 발견되기도 하지만, runtime 에 주로 발생한다.

  • OutOfMemoryError
  • StackOverflowError

Exception

역시나 java.lang.Throwable class 의 subclass.
Exception이란, 런타임에 발생하는 원치 않은 혹은 예상치 못한 이벤트를 말한다.
Java 에는 2가지 종류의 exception 이 존재한다.

  • Checked Exceptions
  • Unchecked Exceptions

Checked Exception

컴파일 타임에 check 되는 Exception으로, checked exception 이 throw 되면 반드시 try-catch block 을 통해 exception 을 handling 하거나 "throw" keyword 를 통해서 exception 을 특정해야 한다.

Checked Exception에는 2가지 종류가 있다.

  • Fully Checked Exception
  • Partially Checked Exception

Fully Checked Exception

모든 child class 들도 check 되는 exception

  • IOException
  • InterruptedException

Partially Checked Exception

child class 들은 unchecked 되는 exception

Unchecked Exception

컴파일 타임에 check 되지 않는 Exception.
Java 에서, 아래 두 경우를 제외하고는 모두 checked exception 이다.

  • exceptions under Error
  • RuntimeException

당신의 코드에서 Checked Exception 은 필요 없다

Checked Exception 은 Java 의 biggest mistake 라고도 불린다. 어떤 이들은, "catch" block 이 exception 을 거의 절대 핸들링 하지 못하고, 오히려 실수를 발생시키는 원인일 뿐이라고도 얘기한다.

Checked Exception 의 의도

처음 checked exception 이 생성되었을 때, 개발자들이 가능한 exception 들을 handling 하도록 강제하여, 소프트웨어를 신뢰할 수 있도록 하고자 만들어졌다. 즉, 성공이 아닌 예상 가능한 결과물들을 "recover"하고자 만들어졌다.

Checked Exception 의 문제점

하지만 문제는, checked exception 이 정확히 무엇을 "recovery" 할 것인지가 불명확했다.

또한, checked exception 과 unchecked exception 이 기능적으로 완전히 동일하다는 것이다. Checked exception 이 handling 할 수 없거나, unchecked exception 이 handling 할 수 없는 경우는 존재하지 않는다.

Checked exception 에 대한 가장 큰 논쟁은, 대부분의 exception 이 개발자의 컨트롤에 의해서 수정 될 수 없다는 것이다.

또한, checked exception 은 Java 8에 새롭게 나온 functional programming (lambda, stream...) 들과 전혀 호환되지 않는다.

Ref.

https://www.geeksforgeeks.org/checked-vs-unchecked-exceptions-in-java/
https://literatejava.com/exceptions/checked-exceptions-javas-biggest-mistake/

0개의 댓글