2017-08-06 38 views
-5

當我試圖用我的測試代碼中的文件實例化一個對象時,我遇到未報告的FileNotFoundException的錯誤。我正在使用/創建的類在構造函數中只有一個FileNotFoundException(只有一個構造函數),所以我不太確定爲什麼在聲明對象時要求額外的FileNotFound。FileNotFoundException未報告

//Constructor 
    public readFile(File file)throws FileNotFoundException { 
    //do i need to create a file object here? 
      Scanner inScanFile = new Scanner(file); 
     } 

    ///////////Running Code from JUNIT below////////////// 
     public void Empty(){ 
      File testFile = new File("HARRY_POTTER_TRIVIA.txt"); 
      ReadingClass newReadtest = new ReadingClass(testFile); //Error occurs here 
+1

嗯......「File Not Found」的哪部分你不明白? – JohnG

+0

'Scanner inScanFile = new Scanner(file);'試圖在絕對路徑中查找文件,但該文件不存在,因此會引發異常。 –

+0

如果類中存在FileNotFoundException,爲什麼當我使用該類實例化一個對象時,我得到一個未報告的異常以包含額外的FileNotFoundException。 – samgrey

回答

0
public readFile(File file)throws FileNotFoundException { 
//do i need to create a file object here? 

沒有,爲什麼呢?你已經有一個。

 Scanner inScanFile = new Scanner(file); 

這可以拋出FileNotFoundException,這就是爲什麼這種構造函數要麼將其接住或聲明它拋出它,或者它的基類之一。

} 

///////////Running Code from JUNIT below////////////// 
    public void Empty(){ 
     File testFile = new File("HARRY_POTTER_TRIVIA.txt"); 
     ReadingClass newReadtest = new ReadingClass(testFile); //Error occurs here 

這是因爲readFile()可以拋出FileNotFoundException,所以,同樣,你必須要麼將其接住或聲明你扔它,或者它的基類之一。

+0

這更有意義,但我看不到readFile()如何拋出一個不會被構造函數捕獲的異常。如果你創建一個不存在的文件對象... java仍然可以編譯。 – samgrey