如何简化/重用这个异常处理代码 [英] How to simplify/reuse this exception handling code

查看:125
本文介绍了如何简化/重用这个异常处理代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  BufferedWriter w = null; //或任何其他抛出异常并且需要关闭的对象
try {
w = new BufferedWriter(new FileWriter(file));
//用w
} catch(IOException e){
e.printStackTrace();
} finally {
if(w!= null){
try {
w.close();
} catch(IOException e){
e.printStackTrace();
}
}
}

它通常涉及一个对象抛出异常并需要关闭,并且关闭它也可能会引发异常。



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

解决方案

我通常把你的最终的内容块放在帮忙中。像这样

  void close(Closeable c){
if(c!= null){
try {
c.close();
} catch(IOException e){
//执行日志记录或只是忽略错误
}
}
}
/ pre>

接口由许多类(输入流,数据库连接等)实现,所以这是一般通用助手。


I tend to write code like the following a lot:

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

It usually involves an object that throws exceptions and needs to be closed, and that closing it may also throw an exception.

I was wondering if the above code can be simplified or reused in any way.

解决方案

I usually put contents of your finally block in a helper. Like this

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

Closeable interface is implemented by many classes (input streams, database connections, etc), so this is kinda general-purpose helper.

这篇关于如何简化/重用这个异常处理代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆