예외(Exception)
- 정상적이지 않은 case
예외 처리(Exception handling)
- 정상적이지 않은 case에 대한 적절한 처리 방법
- try-catch: 예외가 발생할 수 있는 코드를 try 블록 안에 넣고, 예외가 발생했을 때 실행할 코드를 catch 블록에 작성한다.
finally
- 예외 발생 여부와 관계없이 항상 실행되는 코드 블록이다. 주로 리소스를 해제하거나 정리하는 데 사용된다.
throw, throws
- throw: 예외를 발생시킴
- throws: 메서드 선언부에 사용되며, 해당 메서드 내에서 처리되지 않고 호출한 곳으로 예외를 전가시킨다.
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class ExceptionExample {
public static void main(String[] args) {
try {
readFile("example.txt");
} catch (IOException e) {
System.out.println("Error reading file: " + e.getMessage());
}
}
public static void readFile(String filename) throws IOException {
try (BufferedReader reader = new BufferedReader(new FileReader(filename))) {
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
// 예외를 로그하거나 사용자에게 피드백을 제공
System.out.println("An error occurred while reading the file: " + e.getMessage());
throw e; // 예외를 다시 발생시켜 호출한 곳으로 전달
}
}
}
파일을 읽는 도중 예외 발생:
readFile 메서드 내부에서 파일을 읽는 동안 IOException이 발생할 경우 (예를 들어, 파일이 존재하지 않거나 읽을 수 없는 경우), readFile 메서드의 catch 블록이 실행된다.
사용자에게 오류 메시지가 출력된다: "An error occurred while reading the file: [실제 오류 메시지]"
발생한 예외는 throw e; 구문에 의해 다시 발생되고 (rethrown), 이는 readFile 메서드를 호출한 곳으로 전달된다.
메인 메서드에서 예외 처리:
main 메서드의 try-catch 블록이 readFile 메서드로부터 전달된 IOException을 잡아낸다 (catches).
메인 메서드에서 사용자에게 추가적인 오류 메시지가 출력된다: "Error reading file: [실제 오류 메시지]"
An error occurred while reading the file: example.txt (No such file or directory)
Error reading file: example.txt (No such file or directory)
💡 이렇게 두 번의 오류 메시지가 출력되는 이유는 readFile 메서드에서 예외를 잡아내어 로그를 남기고 (catch), 다시 그 예외를 main 메서드로 전달하여 (throw) 추가적인 처리를 하기 때문이다. 이는 예외 상황을 더 명확하게 파악하고 적절히 대응하는 데 도움이 된다.