bijx
bijx

Reputation: 59

Can I throw a FileNotFoundException for any method, or is it only for main method?

I have a program that is suppose to save information to a file using File IO when the user presses the 'x' at the top of the GUI, but when I put the throws FileNotFoundException in the main method, it won't compile without errors.

My code for that section is this:

public void windowClosing(WindowEvent e) {




File myFile = new java.io.File("GuidanceAppt.txt");
PrintWriter output = new PrintWriter(myFile);
for (int i=0;i!=1000;i++){
    output.println(studentNum[i] + " " + name[i] + " " + time + " " + counselor + " ");

}


}

Am I able to do add the throw at the top?

public void windowClosing(WindowEvent e)throws FileNotFoundException {




File myFile = new java.io.File("GuidanceAppt.txt");
PrintWriter output = new PrintWriter(myFile);
for (int i=0;i!=1000;i++){
    output.println(studentNum[i] + " " + name[i] + " " + time + " " + counselor + " ");

}

}

Upvotes: 1

Views: 150

Answers (3)

TNT
TNT

Reputation: 2920

If your class implements WindowListener, you will not be able to add throws FileNotFoundException at the top because your class will not correctly override the windowClosing method. What you need to do instead is use a try-catch block around the methods that can throw a FileNotFoundException:

try {
    File myFile = new java.io.File("GuidanceAppt.txt");
    PrintWriter output = new PrintWriter(myFile);
    for (int i=0;i!=1000;i++){
        output.println(studentNum[i] + " " + name[i] + " " + time + " " + counselor + " ");
} catch (FileNotFoundException ex) {
    ex.printStackTrace();
}

A good way to check if you're correctly overriding methods is to use the @Override annotation, which is place before a method:

@Override public void windowClosing(WindowEvent ev) 
    throws FileNotFoundException { // compilation error

@Override public void windowClosing(WindowEvent ev) {

Upvotes: 0

If you are overriding a method in a superclass (like WindowAdapter) or implementing a method in an interface (like WindowListener) then your override can only declare thrown exceptions which the superclass/interface method also declares.

Since windowClosing in WindowListener declares no exceptions, your override isn't allowed to declare any exceptions either.

Methods that are not overrides or interface implementations can throw whichever exceptions you want.

Upvotes: 0

jnd
jnd

Reputation: 754

You can do that but you will eventually have to deal with the exception. If you don't, then while it is running it may exit unhappily.

One way is to surround with a try and catch block. And tell the user about the file not existing, or to create it.

Upvotes: 1

Related Questions