I am trying to try and catch an error in my method to write the contents of change drawer to a html document. The error, java.io.FileNotFoundException, appears when the file does not exist. The code below should do this but it comes up with the error “PartB is an incompatible type”. I think there is an error in my try and catch code, this the first one I’ve written and I am at a loss as to why it won’t work. Any help would be great. Thankyou.
...
public static void writeHtmlFile()
{
try {
BufferedReader in = new BufferedReader((new FileReader("changedrawer.html")));
String sLine;
StringBuilder sb = new StringBuilder();
while ((sLine = in.readLine()) !=null)
sb.append(sLine+"\n");
//Close file
in.close();
//Output on console
System.out.println(sb.toString());
}
catch (PartB FileNotFoundException) //Why is PartB an incompatible type? (PartB is the name
of the class)
{ System.out.println ("error");
}
...
The syntax for a simple “catch” clause is roughly as follows:
The
<exception-type>is the name if the exception you are trying to catch, and<identifier>is the name of a local variable that you are declaring to hold the exception instance that you just caught.In your cause, it should look like this:
… though I’d recommend a more informative error message!
(Note that you have to declare a local identifier, even if you are not going to use it. But it is only a couple of characters, especialy if you use the conventional names
eorex.)