阿摩線上測驗 登入

申論題資訊

試卷:104年 - 104 鐵路特種考試_高員三級_資訊處理:程式語言#22432
科目:程式語言
年份:104年
排序:0

申論題內容

四、新的程式語言都會提供例外處理(exception handling)。請說明下列 Java 程式做例外
處理的可能流程。並且請說明 finally clause 的執行過程。(20 分)
public void writelist() throws ArrayIndexOutOfBoundsException {
PrintStream pStr = null;
try {
pStr = new PrintStream(
new BufferedOutputStream(
new FileOutputSteam("outfile")));
pStr.println("The 9th element is " +
victor.elementAt(9));
} catch (IOException e) {
System.err.println("i/o error");
} finally {
if (pStr != null) pStr.close();
}
}

詳解 (共 1 筆)

詳解 提供者:hchungw
Java 程式中的例外處理流程
在 Java 中,例外處理是通過 try, catch, 和 finally 區塊來實現的。這段程式碼使用了例外處理來處理可能發生的輸入/輸出錯誤和數組索引越界錯誤。以下是這段程式碼的執行流程及 finally 區塊的說明:
java
複製程式碼
public void writelist() throws ArrayIndexOutOfBoundsException {
    PrintStream pStr = null;
    try {
        pStr = new PrintStream(
            new BufferedOutputStream(
            new FileOutputStream("outfile")));
        pStr.println("The 9th element is " + victor.elementAt(9));
    } catch (IOException e) {
        System.err.println("i/o error");
    } finally {
        if (pStr != null) pStr.close();
    }
}
執行流程說明
初始化變數
PrintStream pStr = null; 初始化 PrintStream 變數 pStr 為 null。
進入 try 區塊
try 區塊開始執行。目的是在這裡執行可能會引發例外的程式碼。
創建文件輸出流
pStr = new PrintStream(new BufferedOutputStream(new FileOutputStream("outfile")));
這行程式碼試圖創建一個新的 PrintStream,該 PrintStream 會向 outfile 文件寫入資料。這裡可能會引發 FileNotFoundException 或 IOException。
寫入文件
pStr.println("The 9th element is " + victor.elementAt(9));
試圖打印 victor 中的第九個元素到文件中。這裡可能會引發 ArrayIndexOutOfBoundsException,如果 victor 的長度小於 10。
捕捉例外
如果在 try 區塊中的任何一行程式碼引發了 IOException,則控制權會轉到 catch 區塊。
catch (IOException e) { System.err.println("i/o error"); }
這段程式碼捕捉 IOException 並輸出 "i/o error" 到標準錯誤流。
執行 finally 區塊
無論 try 區塊中是否引發了例外,finally 區塊中的程式碼都會執行。
finally { if (pStr != null) pStr.close(); }
這段程式碼檢查 pStr 是否為 null,如果不是則關閉 PrintStream,以確保文件資源正確釋放。
finally 區塊的執行過程
保證執行: finally 區塊中的程式碼會在 try 和 catch 區塊後無條件執行,無論是否發生例外。
資源釋放: finally 區塊通常用於釋放資源,例如關閉文件流、釋放鎖等,以避免資源洩露。
執行順序:
如果 try 區塊中的程式碼順利執行完畢,則直接執行 finally 區塊。
如果 try 區塊中引發了例外,控制權轉移到對應的 catch 區塊執行,然後執行 finally 區塊。
如果在 try 區塊或 catch 區塊中發生了 return、break 或 continue,在這些操作之前會先執行 finally 區塊。
綜合說明
這段程式碼的設計確保了即使在發生例外的情況下,文件輸出流 pStr 也會被正確地關閉,以避免資源洩露。這是良好編碼實踐的一部分,有助於提高程式的健壯性和可靠性。