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?