如何在 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)
廣告