시스템에 회복탄력성을 제공하는 메커니즘
Q. try catch문의 정확한 기능은 무엇인가?
흔히 catch문의 기능을 언급할 때 예외를 잡는다고 표현한다. 그러나, 설명이 불충분한 측면이 있다. 왜 잡느냐가 빠져있기 때문이다. 나는 보통 try-catch문을 이용할 때 catch문에서 예외가 잡히면 debugprint를 터미널에 찍는 식으로 이용해왔다. 그러나 이것은 예외 알림에 가깝지 예외 처리에 해당하지 않는다. 발생한 예외에 대한 실질적 대비책이 아니기 때문이다. 만약 catch문이 예외 알림의 기능만 했다면 catch문을 사실상 또 하나의 메소드처럼 쓸 수 있는 수준의 자유도를 주지는 않았을 것이다.
정상 흐름에서 벗어난 동작에 대한 처리를 마련함으로써 다시 프로그램이 정상적으로 동작할 수 있도록 돌려놓는 기능을 하는 것이 try-catch문의 정확한 기능이라고 볼 수 있겠다.
Q. catch문은 무언가를 잡는 역할을 한다. Java에서는 정확히 무엇을 잡는 것인가?
Throwable class를 상속받는 모든 타입의 예외
근거:
Each catch block is an exception handler that handles the type of exception indicated by its argument.
→ catch block은 특정 타입의 예외 인자를 핸들링하는 역할을 함.
The argument type, ExceptionType, declares the type of exception that the handler can handle and must be the name of a class that inherits from the Throwable class.
→ 이 특정 타입의 예외들은 Throwable class를 상속받아야 함.
출처:
https://docs.oracle.com/javase/tutorial/essential/exceptions/catch.html
The catch Blocks (The Java™ Tutorials > Essential Java Classes > Exceptions)
The Java Tutorials have been written for JDK 8. Examples and practices described in this page don't take advantage of improvements introduced in later releases and might use technology no longer available. See Dev.java for updated tutorials taking advantag
docs.oracle.com
Q. catch block을 다중으로 선언할 때 각 block 간 순서가 중요한 이유는?
try {
System.out.println("normal");
} catch (Exception e) { // <----------- 무조건 여기에서 어떤 예외든 다 잡히므로
} catch (ArrayIndexOutOfboundsException e) { // <---- 아무런 의미가 없는 코드
}
위와 같이 모든 예외 클래스의 부모에 해당하는 Exception이 먼저 와버리면 후속 catch는 아무런 쓸모가 없어지기 때문에 컴파일 타임에서 에러를 뱉기 때문이다.
대신, 자식 예외 클래스들을 catch문의 전방에 배치하고 Exception은 이 자식들이 혹여 놓칠 수도 있는 예외를 잡는 용도로 맨 마지막에 배치하는 것이 좋다.
Q. exception은 error, checked exception, unchecked exception으로 나뉜다. 이때 checked? 정확히 무엇을 check하는 것인가?
catch block의 존재 유무를 check한다.
근거:
Java programming language requires that a program contains handlers for checked exceptions
→ handler가 존재하는지 여부를 check한다.
Handlers are established by catch clauses of try statements
→ handler는 catch 절에서 구축된다.
출처:
https://docs.oracle.com/javase/specs/jls/se7/html/jls-11.html
'프로그래밍 언어 > Java' 카테고리의 다른 글
[Java]extends vs implements: 단일 vs 다중 상속 (0) | 2025.05.28 |
---|---|
객체가 같다는 것은 정확히 어떤 의미인가? (0) | 2025.05.28 |
Garbage collection (0) | 2025.05.28 |