在我的代码中,我的一种方法说:
this.write("stuff")
,写方法是
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();
}
事情说有一个
FileWriter "unreported exception java.io.IOException; must be caught or declared to be thrown"
。
我应该在try和catch语句中添加什么来修复异常?
答案 0 :(得分:2)
如何处理任何类型的异常对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*/}
}