在真實範例中使用 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");
}
}