error: unreported exception FileNotFoundException; must be caught or declared to be thrown
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
}
}
If you're very new to Java, and just trying to learn how to use PrintWriter
, here is some bare-bones code:
import java.io.*;
public class SimpleFile {
public static void main (String[] args) throws IOException {
PrintWriter writeMe = new PrintWriter("newFIle.txt");
writeMe.println("Just writing some text to print to your file ");
writeMe.close();
}
}
a PrintWriter
might throw an exception if there is something wrong with the file, like if the file doesn't exist. so you have to add
public static void main(String[] args) throws FileNotFoundException {
then it will compile and use a try..catch
clause to catch and process the exception.