2016-07-02 31 views
-4

在我的代碼,我的方法之一說:不知道如何處理的FileWriter異常

this.write("stuff") 

和write方法是

public void write(String text) throws IOException 
{ 
    FileWriter writer = new FileWriter(path, true); 
    PrintWriter printer = new PrintWriter(writer); 
    printer.printf("%s" + "%n", text); 
    printer.close(); 
} 

事情說有一個 "unreported exception java.io.IOException; must be caught or declared to be thrown"爲FileWriter。

我應該在try和catch語句中修復異常?

+2

你應該把你的電話給'this.write' try塊,趕在錯誤中提到的例外消息,然後優雅地對其進行處理。但是瞭解Java程序員,你可能只需要放入一個'printStackTrace'調用,而忘記其餘部分。 –

+0

你說這個方法拋出一個異常,但是你不用try/catch塊來捕獲異常 – Li357

+0

你需要處理異常。請參閱[捕獲和處理異常](https://docs.oracle.com/javase/tutorial/essential/exceptions/handling.html) – copeg

回答

0

如何處理任何類型的異常對Java開發至關重要。 有兩種方法可以做到這一點:

public void write(String text) //notice I deleted the throw 
{ 
    try{ 
     FileWriter writer = new FileWriter(path, true); 
     PrintWriter printer = new PrintWriter(writer); 
     printer.printf("%s" + "%n", text); 
     printer.close(); 
    catch(IOException ioe){ 
     //you write here code if an ioexcepion happens. You can leave it empty if you want 
    } 
} 

和...

public void write(String text) throws IOException //See here it says throws IOException. You must then handle the exception when calling the method 
{ 
    FileWriter writer = new FileWriter(path, true); 
    PrintWriter printer = new PrintWriter(writer); 
    printer.printf("%s" + "%n", text); 
    printer.close(); 
} 

//like this: 
public static void main(String[] args) //or wherever you are calling write from 
{ 
    try{ 
      write("hello"); //this call can throw an exception which must be caught somewhere 
     }catch(IOException ioe){/*whatever*/} 
}