public static void generateOutput() {
File file = new File ("C:/Users/me/Desktop/file.txt");
PrintWriter outputFile = null;
outputFile = new PrintWriter(file);
}
Above is my code, I am trying to make a PrintWriter that writes to a file I have made on my desktop called file.txt, however I am getting the error "unhandled exception type, file not found exception". I have looked at other posts and I'm unsure why I am still getting this error. I have also tried doing so without the File object. I was hoping for some guidance as to where I went wrong
The most important idea you have to understand here, is that your file may:
In all above cases, your Java program, triggering OS Kernel, will crush, and the exception will happen at the runtime. In order to avoid this accident, Java designers decided (and well they did), that PrintWriter
should throw (meaning, it is a possibility to throw) FileNotFoundException
and this should be a checked exception at compile time. This way developers will avoid more serious run-time problems, like program crush crush.
Hence, you either have to:
try-catch
in your method that PrintWriter; orI think, your question was about why that happens. Here is the answer for both - (1) why? and (2) how to solve it.