2014-04-05 63 views
0

我不斷收到FileNotFoundException,即使I'm把它扔。任何幫助,將不勝感激:)錯誤:未報告的異常java.io.FileNotFoundException;必須捕獲或聲明拋出[7]

Here's代碼:

import java.util.*; 
import java.io.*; 

public class kt_6_2 { 
    public static void main(String[] args) { 
     File file = new File("magicSquare.txt"); 
     fileRead(file); 
    } 
    static void fileRead (File dummyFile) throws FileNotFoundException { 
     Scanner scanner = new Scanner(dummyFile); 
     String[] squareLines = new String[3]; 
     for (int a = 0; a < 3; a++) { 
      squareLines[a] = scanner.nextLine(); 
      scanner.nextLine(); 
     } 
     System.out.println(squareLines[2]); 
    } 
} 

Ninjaedit-錯誤消息:

kt_6_2.java:7: error: unreported exception FileNotFoundException; must be caught 
or declared to be thrown 
       fileRead(file); 
         ^
1 error 

回答

4

由於您的主要方法是調用您的fileRead()方法。而不是處理異常你的fileRead()方法決定拋出異常。

因此,在例外情況下,一旦從fileRead()方法拋出,應該在您的main()方法中捕獲它。但是,你的main()可以進一步拋出這個異常。

你需要寫爲

public static void main(String[] args) throws FileNotFoundException { 
.... 

,或者如果你想處理異常,你應該寫:

public static void main(String[] args) { 
    File file = new File("magicSquare.txt"); 
    try{ 
     fileRead(file); 
     } catch (FileNotFoundException ex) { 
      //exception handling code 
     } 
    } 
+0

感謝。我添加了「拋出FileNotFoundException異常」的main()方法,但現在我有兩個人,一個在main(),一個在FILEREAD方法。這是一個錯誤還是對的? – user3207874

+1

從句法上看,它是正確的。但是一般來說,你應該捕獲你的編譯時(checked)異常並且做適當的處理/處理而不是盲目地拋出它。 – sakura

1

must be caught or declared to be thrown

究竟你這裏不明白嗎? 您使用的方法fileRead會拋出FileNotFoundException,因此您必須追上它,或者向上手,所以你main方法需要一個throws子句。

但後者的選擇,當然,一個壞的。因此,只需在try/catch塊中包裝readFile調用即可。

相關問題