我可以错过catch子句向其调用者抛出异常吗?

时间:2013-04-20 08:46:47

标签: java exception finally

此代码可能会出现什么问题? 我认为即使发生异常,此代码也可以将异常抛给其调用者。 所以它不会产生任何麻烦。

我该如何改进?

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

3 个答案:

答案 0 :(得分:2)

代码必须抛出IOException - 尝试使用eclipse编辑代码,你也会得到一个抛出异常的建议。

Java 1.7也有“try-with-resources”的新概念 - 请参阅下面的try语句。 try (...)中使用的资源会自动关闭。

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

答案 1 :(得分:1)

  

此代码可能会出现什么问题?

public class FileNotFoundException extends IOException

您可以将方法更改为:

public static void cat(File named) throws IOException

现在您不需要 try-catch 块。

调用者应该捕获方法抛出的exception

但为什么不想catch例外?

答案 2 :(得分:0)

在你的方法中添加throws声明,然后这个方法的调用者应该为这个异常尝试catch块。

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)
    {
      //
    }
相关问题