iT邦幫忙

2026 iThome 鐵人賽

DAY 24
0

本日學習:
檔案處理補充

  1. FileInputStream:
    • 處理位元組串流
    • 建構子:FileInputStream(String name)
    • 函數:
      int avalible():取得讀取資料所占的位元組數
      void close()
      long skip(long n)
      int read()
      int read(byte[] b)
      int read(byte[] b, int off, int len)
  2. FileOutputStream:
    • 建構子:
      FileOutputStream(String filename)
      FileOutputStream(String name, Boolean a)
    • 函數:
      void close()
      void write(byte[] b)
      void write(byte[] b, int off, int len)

例外處理

  1. 所有例外都是以類別形式存在
  2. try{要檢查的程式敘述} catch(例外類別 變數名稱){例外發生時的處理順序} finally{一定會執行的程式碼;}
    • 變數名稱為例外類別所建立的物件
  3. 判別 try 程式區塊是否有例外產生、例外是否和 catch() 內欲捕捉的例外相同
  4. {} 不能省略
  5. finally{} 可省略
  6. 例外處理:預設機制 or try/catch/finally 兩種方式處理
  7. 例外類別:java.lang.Throwable,以下又分為兩種:error、exception
    • catch() 括號內只接受 Throwable 子類別所產生的物件
    • error:記憶體不足、硬體故障等,通常無法由程式碼進行修復
    • exception:例如檔案不存在、格式錯誤,加入適當例外檢查可確保程式繼續執行
      RuntimeException:也不強制受檢查
  8. 使用 try 捕捉一種以上的例外:catch() 寫兩次,範圍小的放前面
  9. 想捕捉所有例外就寫 exception

拋出與接收例外

  1. throw 由例外所產生的物件;
    • 例如:
public class Ch24_1{
    public static void main(String[] args){
        int a = 4, b = 0;
        try{
            if(b == 0)
                throw new ArithmeticException();
            else
                System.out.println(a + "/" + b + "/" + "=" + a/b)
        }
        catch(ArithmeticException e){
            System.out.println(e + " throwed");
        }
    }
}

throw new ArithmeticException(); 不一定要寫,沒寫系統也會自動拋出
2. 由函數拋出例外:未使用 try/catch/finally 時
- 函數名稱(引數 ......) throws 例外類別1, 例外類別2, ......{函數內的程式碼;}
- 使用 throws 指定函數拋出例外
- 例如:

public class Ch24_2{
    public static void aaa(int a, int b) throws ArithmeticException{
        int c;
        c = a / b;
        System.out.println(c);
    }
    public static void main(String[] args){
        try{
            aaa(4, 0);
        }
        catch(ArithmeticException e){
            System.out.println(e + " throwed");
        }
    }
}
  1. 透過繼承自己撰寫例外類別:class 例外類別名稱 extends Exception{}
  2. IOException 例外類別:
    • 處理有關輸入、輸出的例外
    • 通常發生在讀取檔案未完成便被終止
    • 少見

上一篇
Day 23:檔案處理
系列文
從零開始學程式語言:Java 新手修煉記 共 24 篇
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言