-1

I created a new project in IntelliJ and created a new class with the following code:

import java.io.PrintWriter;

public class myWriter {
    public static void main(String[] arg){
        PrintWriter writeMe = new PrintWriter("newFIle.txt");
        writeMe.println("Just writing some text to print to your file ");
        writeMe.close();
    }
}

I expect this to create a txtfile in the working directory containing "Just writing some text to print to your file ". However, it just returned the error:

Error:(5, 31) java: unreported exception java.io.FileNotFoundException; must be caught or declared to be thrown
  • The listed exception type must be caught (add a `try/catch` block) or declared to be thrown (add `throws FileNotFoundException` to your method declaration). – khelwood Apr 30 '19 at 09:49
  • read the error again and again until you know what it means ... I mean come on ... – Pali Apr 30 '19 at 09:51
  • Im very new to java, I know how to do a try/catch but what is 'throws FileNotFoundException' and why do i need to catch an exception if i expect the code to work? – mac demarco Apr 30 '19 at 09:52
  • `FileNotFoundException` is a checked exception. That means the compiler checks your code to make sure that you will handle the exception (or at least declare that it could happen) in any situation where it might occur. – khelwood Apr 30 '19 at 09:58
  • 1
    See [Java: checked vs unchecked exception explanation](https://stackoverflow.com/questions/6115896/java-checked-vs-unchecked-exception-explanation) – khelwood Apr 30 '19 at 10:00
  • I think i get it. So the people who wrote PrintWriter wanted people to be able to handle there not being a file with the name given. So they created a checked exception when using PrintWriter which is like a test for when the file is not found. Is this right? – mac demarco Apr 30 '19 at 10:15
  • I looked up the documentation for PrintWriter [https://docs.oracle.com/javase/7/docs/api/java/io/PrintWriter.html] However It said PrintWriter throws 'FileNotFoundException' _If the given string does not denote an existing, writable regular file and a new regular file of that name cannot be created_ However even after I create a text file in the working directory with that name I still get the exception. why is this? – mac demarco Apr 30 '19 at 10:18

1 Answers1

0

It should be like this (using try/catch) :

try {
       PrintWriter writeMe = new PrintWriter(new File("newFIle.txt"));
       writeMe.println("Just writing some text to print to your file ");
       writeMe.close();
} catch (FileNotFoundException e) {e.printStackTrace();}
nullPointer
  • 4,419
  • 1
  • 15
  • 27