2015-10-18 71 views
1
public FileReader() throws FileNotFoundException { 
    //create fileChooser 
    JFileChooser chooser = new JFileChooser(); 
    //open fileChooser 
    int returnValue = chooser.showOpenDialog(new JFrame()); 
    try { 
     if (returnValue == JFileChooser.APPROVE_OPTION) { 
      file = chooser.getSelectedFile(); 
     } 
    } catch (FileNotFoundException e) { 

    } 
} 

我正在編寫一個程序來讀取文本文件並將其放入一個字符串(單詞)的數組中。這只是程序的文件閱讀器,當我嘗試從代碼的另一部分調用方法時,它給我一個錯誤。任何想法將不勝感激;它可能是一個簡單的修復,我似乎無法找到它。Java使用JFileChooser時未報告的異常

這裏的錯誤:

unreported exception FileNotFoundException; must be caught or declared to be thrown

+0

在哪一行發生? –

+0

實際上,當我在其他地方調用方法時,實際發生這種情況,但這是有問題的代碼 – Carl5444

回答

1

你在這裏比較難以檢查異常。最主要的是,FileNotFoundException被選中,它必須:

  • try...catch聲明在其使用點被抓,或
  • 宣佈通過該方法的簽名throws聲明被拋出。

不要一般都想同時做這兩個,你現在是這樣。

至於進一步的建議,你也不想做任一:

  • 拋出一個異常,在構造
  • 沒有做一個捕獲的異常

所以我的東西個人建議將是趕上例外和處理它...

public FileReader() { 
    //create fileChooser 
    JFileChooser chooser = new JFileChooser(); 
    //open fileChooser 
    int returnValue = chooser.showOpenDialog(new JFrame()); 
    try { 
     if (returnValue == JFileChooser.APPROVE_OPTION) { 
      file = chooser.getSelectedFile(); 
     } 
    } catch (FileNotFoundException e) { 
     e.printStackTrace(); 
    } 
} 

.. 。但是除非我在看錯誤的庫,I don't see anywhere where a FileNotFoundException is even thrown on JFileChooser!這會讓你的代碼變得很簡單 - 不要在try...catch那裏打擾*。

*:你實際上刪除它,因爲它是一個編譯錯誤,以捕獲從未拋出的檢查異常。

1

聲明該構造函數拋出一個檢查異常:

public FileReader() throws FileNotFoundException 

任何你調用此構造,您必須聲明它從方法,如拋

public static void main(String[] args) throws FileNotFoundException { 
    new FileReader(); 
} 

或抓住它並處理它,例如,

public static void main(String[] args) { 
    try { 
    new FileReader(); 
    } catch (FileNotFoundException e) { 
    // Handle e. 
    } 
} 

,或者,如果沒有在​​拋出一個未捕獲FileNotFoundException(就像在你的代碼,其中FileNotFoundException被捕獲併吞下),該throws FileNotFoundException從​​刪除,例如允許

public static void main(String[] args) { 
    new FileReader(); 
}