Programmers learn & share
0 votes
369 views

Problem :

I want to create a simple program that will output a string to a text file. Below is my code :

import java.io.*;
public class JavaTesting {
public static void main(String[] args) {
File myfile = new File ("myfile.txt");
myfile.getParentFile().mkdirs();
PrintWriter printWriter = new PrintWriter(myfile);
printWriter.println ("Trying to write the txt using Java");
printWriter.close();       
  }
} 

But J-grasp is throwing me the following error:

 ----jGRASP exec: javac -g JavaTesting.java
JavaTesting.java:10: error: unreported exception FileNotFoundException; must be caught or declared to be thrown
PrintWriter printWriter = new PrintWriter(myfile);
                              ^
1 error
 ----jGRASP wedge2: exit code for process is 1.

As I am very new to Java, I am unable to understand the error. Can anybody help me in resolving the error?

by (7.5k points)   | 369 views

1 Answer

0 votes

Solution :

This error is occurring because you are not doing the Exception Handling and not telling compiler that there is a chance to throw a FileNotFoundException. In this situation the  FileNotFoundException will be thrown if the file does not exist.

You can refer below code:

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

}

by (36.1k points)  
2,227 questions
2,734 answers
59 comments
241 users