0

What kind of problem may occur for this code? I think even exception occurs, this code can throw the exception to its caller. So it does NOT generate any trouble.

How can I improve it?

public static void cat(File named) {
  RandomAccessFile input = null;
  String line = null;
  try {
    input = new RandomAccessFile(named, “r”);
    while ((line = input.readLine()) != null {
      System.out.println(line);
    }
    return;
  } finally {
    if (input != null) {
      input.close();
    }
  }
}
Zachery
  • 131
  • 2
  • 8

3 Answers3

2

The code has to throw the IOException - try editing your code with eclipse and you would also get a suggestion to throw the Exception.

Also Java 1.7 has the new concept of "try-with-resources" - see the try statement below. The resource used in try (...) is closed automatically.

public static void cat(File named) throws IOException
{
    try (RandomAccessFile input = new RandomAccessFile(named, "r"))
    {
        String line = null;
        while ((line = input.readLine()) != null)
        {
            System.out.println(line);
        }
    }
}
michael_s
  • 2,515
  • 18
  • 24
  • 3
    you do not need a try-catch-finally block if you force the method to throw any exception – shiladitya Apr 20 '13 at 08:59
  • 2
    oh? - the "try-with-resource" is used for closing the file - no need to down-vote in case you don't know what you're talking about, right? – michael_s Apr 20 '13 at 09:00
1

What kind of problem may occur for this code?

Since public class FileNotFoundException extends IOException

You can change your method to:

public static void cat(File named) throws IOException

And now you don't need a try-catch blocks.

And the caller should catch the exception thrown by the method.

But why don't you want to catch the exceptions?

Maroun
  • 94,125
  • 30
  • 188
  • 241
0

add the throws declaration in your method , and then caller of this method should have try catch block for this exception .

public static void cat(File named) throws IOException {
      RandomAccessFile input = null;
      String line = null;
      try {
        input = new RandomAccessFile(named, "r");
        while ((line = input.readLine()) != null ){
          System.out.println(line);
        }
        return;
      } finally {
        if (input != null) {
          input.close();
        }
      }
    }
  //caller 
   try{
     Class.cat(new File("abc.txt"));
    }catch(IOException e)
    {
      //
    }
Ahsan
  • 29
  • 1