Skip to Main Content

New to Java

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

FileReader - unreported exception must be caught or declared to be thrown

843789Apr 6 2010 — edited Apr 6 2010
Hi. I'm a beginner to Java working on my first big project. I have read all sorts of tutorials on Exceptions and searched this error all over the internet but no answers seem to work.

I'm simply trying to add a method that would open a file and print its contents to terminal. Shouldn't be too difficult.

I'm getting the following error:

unreported exception java.io.IOException; must be caught or declared to be throw

Now, this comes from my readFile(String s) method which, by itself, compiles perfectly. But when i add a call to the readFile method from a GUI button i get the obnoxious error.
public void readFile(String s) throws IOException 
    {
        String fileName = s;
        FileReader reader = null;
        try {
            reader = new FileReader(fileName);
            int code = reader.read();
            while (code != -1) {
                char ch = (char)code;
                System.out.print(ch);
                code = reader.read();
            }
        } catch (IOException e) {
            System.out.println(e.getMessage());
        } finally {
            if (reader != null) reader.close();
        }
    }
}
Again, this compiles ok. But when I add this to a JButton in the same class (which extends JMenuBar) as such:
JMenuItem controlsItem = new JMenuItem("Controls");
        controlsItem.addActionListener(new ActionListener() {
                                public void actionPerformed(ActionEvent e) {
                                    readFile("controls.txt");

                                }
 
Then I get unreported exception java.io.IOException; must be caught or declared to be thrown

Any ideas please?
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on May 4 2010
Added on Apr 6 2010
5 comments
3,892 views