2016-07-02 27 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*/} 
}