如何简化/重用此异常处理代码

hpi*_*que 5 java code-reuse exception-handling exception

我倾向于编写如下代码:

BufferedWriter w = null; // Or any other object that throws exceptions and needs to be closed
try {
    w = new BufferedWriter(new FileWriter(file));
    // Do something with w
} catch (IOException e) {
    e.printStackTrace();
} finally {
    if (w != null) {
        try {
            w.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

它通常涉及一个抛出异常并需要关闭的对象,关闭它也可能会抛出异常.

我想知道上述代码是否可以以任何方式简化或重用.

She*_*ari 6

如果你不想编写关闭finally块的代码,你应该看看Project Lombok

而不是写正常

public class CleanupExample {
  public static void main(String[] args) throws IOException {
  InputStream in = new FileInputStream(args[0]);
  try {
    OutputStream out = new FileOutputStream(args[1]);
    try {
      byte[] b = new byte[10000];
      while (true) {
         int r = in.read(b);
         if (r == -1) break;
         out.write(b, 0, r);
      }
    } finally {
        out.close();
      }
  } finally {
     in.close();
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

有了Lombok,你可以写

public class CleanupExample {
  public static void main(String[] args) throws IOException {
    @Cleanup InputStream in = new FileInputStream(args[0]);
    @Cleanup OutputStream out = new FileOutputStream(args[1]);
    byte[] b = new byte[10000];
    while (true) {
      int r = in.read(b);
      if (r == -1) break;
      out.write(b, 0, r);
    }
   }
 }
Run Code Online (Sandbox Code Playgroud)

更具可读性,它可以生成关闭Stream的正确方法.这适用于所有Closeable接口


Nik*_*bak 5

我通常把你的finally块的内容放在帮助器中.像这样

void close(Closeable c) {
    if (c != null) {
        try {
            c.close();
        } catch (IOException e) {
            // perform logging or just ignore error
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Closeable 接口由许多类(输入流,数据库连接等)实现,因此这是一种通用的帮助器.