Initializing disposable resources outside or inside try/finally

喜欢而已 提交于 2019-12-05 20:15:34

In C#, just use the using statement:

using (Resource resource = GetResource())
{
    /* Do something */
}

This is the idiomatic way of cleaning up resources, and relies on the resource in question implementing the IDisposable interface. (Java now has a similar try-with-resources statement, for resources implementing AutoCloseable.)

There's no risk of a thread abort in Java happening between the assignment and entering the try block - aborts only occur during sleeps and waits. EDIT: I can't actually find this in the spec, which is somewhat worrying. Hmm.

first one is preferable

If getResource() throws an exception then resource will be null, getResource() does not return anything in the case of an exception. So, as long as getResource() can throw an exception, always check for null before calling resource.close(). I feel the best way to organize this code is to put everything inside the try block; make it clear clear that getResource() throws exceptions.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!