如何在 Java 中捕獲檔案未找到異常?


在使用 FileInputStream、FileOutputStream 和 RandomAccessFile 類時,我們需要將檔案路徑傳遞給它們的建構函式。如果指定路徑中沒有檔案,就會引發 FileNotFoundException。

示例

public class Sample {
   public static void main(String args[]) throws Exception {
      File file = new File("myFile");
      FileInputStream fis = new FileInputStream(file);
      System.out.println("Hello");
   }
}

輸出

Exception in thread "main" java.io.FileNotFoundException: myFile
(The system cannot find the file specified)
      at java.io.FileInputStream.open(Native Method)
      at java.io.FileInputStream.open(Unknown Source)
      at java.io.FileInputStream.<init>(Unknown Source)
      at a5Exception_Handling.NullPointer.main(NullPointer.java:10)

更新於: 20-Feb-2020

313 次瀏覽

開啟您的職業生涯

完成課程以獲得認證

立即開始
廣告