-3

In my code, one of my methods says:

this.write("stuff")

and the write method is

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();
}

The thing says that there is an "unreported exception java.io.IOException; must be caught or declared to be thrown" for the FileWriter.

What should I put in the try and catch statements to fix the exception?

user207421
  • 305,947
  • 44
  • 307
  • 483
Andriy F.
  • 15
  • 1
  • 2
  • 3
    You should put your call to `this.write` in the try block, catch the exception it mentioned in the error message, and then handle it gracefully and accordingly. But knowing Java programmers you'll probably just put in a `printStackTrace` call and forget about the rest. – Matti Virkkunen Jul 02 '16 at 21:36
  • You say the method throws an exception but you don't use a try/catch block to catch the exception – Andrew Li Jul 02 '16 at 21:36
  • You need to handle the Exception. See [Catching and Handling exceptions](https://docs.oracle.com/javase/tutorial/essential/exceptions/handling.html) – copeg Jul 02 '16 at 21:36
  • 2
    The `write` method is fine - it throws an `IOException`. Seems the issue is with the method **calling** `write`. Can you share its code please? – Mureinik Jul 02 '16 at 21:37
  • 2
    No, actually, the write method isn't right. It should always close the FileWriter, even if an exception is thrown. It should use the try-with-resources statement to make sure that happens. – JB Nizet Jul 02 '16 at 22:01
  • There is no issue with `FileWriter` exceptions in this code. Unclear what you're asking. – user207421 Jul 02 '16 at 23:13

1 Answers1

2

How to handle any kind of exception is essential to Java development. There is two ways to do it:

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
    }
}

and...

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*/}
}
Carlos
  • 121
  • 1
  • 1
  • 8