실제 예제에서 finally 사용하기
Finally 블록은 일반적으로 데이터베이스나 파일처럼 사용 중인 리소스를 정상 흐름이든 예외가 발생했든 관계없이 닫고 정리하는 데 사용합니다.
여기서는 파일 열기, 파일에 텍스트 쓰기, 파일 닫기를 모두 메서드 호출로 시뮬레이션합니다. 예외 발생 여부와 상관없이 시뮬레이션된 파일을 닫기 위해 finally를 사용하세요.
이 연습은 강의의 일부입니다
Java의 데이터 타입과 예외
연습 안내
- 파일을 열고 파일에 쓰는 작업을 감싸는 try 블록을 시작하세요.
- 시뮬레이션된 파일을 열거나 그 안에 텍스트를 쓰는 동안 발생할 수 있는 모든 예외를 포착하세요.
- 프로그램이 문제없이 실행되든, 파일을 열거나 파일에 쓰는 중 예외가 발생하든 호출되도록, 시뮬레이션된 파일을 닫는 finally 블록을 추가하세요.
실습형 인터랙티브 연습
이 예제를 이 샘플 코드를 완성하여 풀어보세요.
public class FinallyCleanup {
public static void main(String[] args) {
String[] words = { "Lorem", "ipsum", "dolor", "sit", "amet" };
// Open a try block
____ {
open();
for (int i = 0; i <= words.length; i++) {
writeToFile(words[i]);
}
// Catch any possible exception
} ____ (____ ____) {
System.out.println("Problem writing words to file");
// Add a finally block to close the file
} ____ {
close();
}
}
public static void open() {
System.out.println("Our file is open");
}
public static void close() {
System.out.println("Our file is closed");
}
public static void writeToFile(String text) {
System.out.println(text + " has been written to the file");
}
}