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

user2956248 picture user2956248 · Nov 5, 2013 · Viewed 69.9k times · Source

I'm trying to create a simple program that will output a string to a text file. Using code I found here, I have put together the following code:

import java.io.*;

public class Testing {

  public static void main(String[] args) {

    File file = new File ("file.txt");
    file.getParentFile().mkdirs();

    PrintWriter printWriter = new PrintWriter(file);
    printWriter.println ("hello");
    printWriter.close();       
  }
} 

J-grasp throws me the following error:

 ----jGRASP exec: javac -g Testing.java

Testing.java:10: error: unreported exception FileNotFoundException; must be caught or declared to be thrown
    PrintWriter printWriter = new PrintWriter(file);
                              ^
1 error

 ----jGRASP wedge2: exit code for process is 1.

Since I'm pretty new to Java, I have no idea what this means. Can anybody point me in the right direction?

Answer

06needhamt picture 06needhamt · Nov 5, 2013

You are not telling the compiler that there is a chance to throw a FileNotFoundException a FileNotFoundException will be thrown if the file does not exist.

try this

public static void main(String[] args) throws FileNotFoundException {
    File file = new File ("file.txt");
    file.getParentFile().mkdirs();
    try
    {
        PrintWriter printWriter = new PrintWriter(file);
        printWriter.println ("hello");
        printWriter.close();       
    }
    catch (FileNotFoundException ex)  
    {
        // insert code to run when exception occurs
    }
}