• Register
0 votes
1.3k 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?

6 5 3
7,540 points

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
}

}

9 7 4
38,600 points

Related questions

1 vote
2 answers 304 views
304 views
Problem : I am very new to Java. I am trying to execute my Java code but facing below error. filecontent.java:25: unreported exception java.io.IOException; must be caught or declared to be thrown showfile(); ^ filecontent.java:88: unreported exception java.io. ... or declared to be thrown showfile(); ^ I have already thrown the java.io.IOException, however still it shows me above errors.
asked Dec 28, 2019 alecxe 7.5k points
0 votes
1 answer 4 views
4 views
I have a Java project I am working on and I get this error.
asked 18 hours ago TeamScript 3.7k points
0 votes
1 answer 726 views
726 views
Problem : I am facing a problem with the exception handling in Java, following is my code. I am facing compiler error when I try to execute my code. The error is as below: exception MojException is never thrown in body of corresponding try ... MyMojException: public class MyMojException extends Exception{ MyMojException(String str){ super(str); } } Can anyone suggest solution on my issue?
asked Dec 5, 2019 alecxe 7.5k points