This discussion is archived
4 Replies Latest reply: Apr 22, 2008 7:02 AM by 807601 RSS

How to throw or catch IOException?

807601 Newbie
Currently Being Moderated
Hi,
I am very simply trying to write a method for a class to print the objects info to a file (to test a hw assignment, don't worry, it's not the actual assignment, so I'm not trying to get anyone to do my work for me =D). Unfortunately, since I'm declaring the printwriter outside of any method, I can't figure out how to deal with the "Slider.java:35: unreported exception java.io.IOException; must be caught or declared to be thrown" message the compiler gives.
here is the important part of the code, any suggestions?:


import java.util.*;
import java.io.*;

public class Slider     
{

//          Instance Data Members     
String slider[][];
int size;
PrintWriter toFile = new PrintWriter(new FileWriter("moves.txt"), true);                    

public Slider(int s)
{
size = s;
slider = new String[size][size];
iblank = size-1;
jblank = size-1;

for (int i=0; i<size; i++)
{
for (int j=0; j<size ; j++)
{
slider[i][j]= Integer.toString(i*size + j + 1);
}
}
slider[iblank][jblank] = "";
}


          public void printToFile()     throws IOException
          {
for (int i=0; i<size ; i++)
{
for (int j=0; j<size ; j++)
{     toFile.printf("%4s", slider[i][j]);     }
     
toFile.println();
}
toFile.println();
}
  • 1. Re: How to throw or catch IOException?
    800308 Newbie
    Currently Being Moderated
    Which is line 35?
  • 2. Re: How to throw or catch IOException?
    807601 Newbie
    Currently Being Moderated
    Where ever you call printToFile() u must either throw IOException or catch the same
  • 3. Re: How to throw or catch IOException?
    800308 Newbie
    Currently Being Moderated
    and format your code properly FFS... and post it between code tags
    /**
     * prints the matrix to the given PrintWriter
     * @param writer PrintWriter - to write to.
     */
    public void print(PrintWriter writer) throws IOException {
      for (int i=0; i<size ; i++) {
        for (int j=0; j<size ; j++) {
          writer.printf("%4s", slider[i][j]); 
        }
        writer.println();
      }
      toFile.println();
    }
    ... and just pass the PrintWriter into the print method
  • 4. Re: How to throw or catch IOException?
    807601 Newbie
    Currently Being Moderated
    thanks everyone for the replies!

    sorry for my bad coding, I was planning on adding all the javadoc comments when I finished debugging. Also, I cut and pasted from my (relatively) long and complicated code to show the parts that mattered so line 35 is: PrintWriter toFile = new PrintWriter(new FileWriter("moves.txt"), true);

    Do you (you being corlettk) mean put the printwriter inside my printToFile method? if so, the reason I don't want to do that is because I don't want to overwrite the file every time I call the method, I want to add to the existing file...

    thanks again for helping!