Question

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");
     }
     ...
Was it helpful?

Solution

The syntax for a simple "catch" clause is roughly as follows:

} catch (<exception-type> <identifier>) {  
    <optional-statements>
}

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:

catch (FileNotFoundExceptio ex) {
    System.out.println ("error");
}

... 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 e or ex.)

OTHER TIPS

You need to write it as FileNotFoundException PartB, not PartB FileNotFoundException because FileNotFoundException is the type.

You declare an exception like you declare any object or variable:

Exception_Type identifier

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top