简体   繁体   中英

Can I miss the catch clause to throw exception to its caller?

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();
    }
  }
}

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);
        }
    }
}

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?

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)
    {
      //
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM