Java中空赋值的优点是什么?
我看到很多像这样的代码:
SomeObject someObject = null; try{ someObject = ObjectFactory.createSomeObject(); ...
与此相比,这样做有什么好处:
SomeObject someObject = ObjectFactory.createSomeObject();
这是一个常用的习惯用法,你必须用null初始化连接,因为Java只支持类成员的初始化,在这个范围内你必须用null
初始化它,因为ConnectionFactory.create()
也可能抛出exception。
您可以使用它来扩展变量的范围并在以后使用它,例如关闭连接句柄。
Connection connection = null; try { connection = ConnectionFactory.create(); [...] // More code which probably causes an exception } catch(Exception e) { // Handle the exception } finally { if(connection != null) { // Cleanup and close resources later connection.close() } }
如果初始化catch块中的连接,则对于finally块或以下代码不可见。
在创建需要销毁的对象或需要处理的资源时,这是一种常见的模式。 例如,使用数据库连接:
Connection connection = null; PreparedStatement statement = null; try { connection = getConnection(); statement = connection.prepareStatement("SELECT * FROM users"); // ... } catch (SQLException exception) { // Handle error. } finally { if (statement != null) statement .close(); if (connection != null) connection.close(); }
如果声明try
块内的对象,则它们不能在finally
内引用,因为它具有不同的作用域。 声明需要在try
之外,但是赋值必须在内部,以便可以捕获初始化期间的exception。
close()
调用必须在finally
块内完成,以确保释放数据库资源,无论数据库调用是否成功。
它可能与someObject-variable的范围(可见性)有关,因此稍后可以在try-catch -block之外使用该变量。
这是一个不明智的小舞蹈人与null
s玩,试图合并一个try
– finally
与try
– catch
。 它经常伴随着错误(NPE,在不开心的情况下没有关闭所有内容,释放未获得的资源等等 – 人们如此富有创造力,有着邋code的代码中的错误)。 将两种不同forms的try
分开,可能分为不同的方法要好得多。 与try
– catch
– finally
组合不同, finally
应该在catch
。
try { final SomeObject someObject = ObjectFactory.createSomeObject(); try { ... } finally { someObject.dispose(); } } catch (SomeException exc) { throw AppropriateToTheCallerException(exc); // or printf }
在JDK7中,假设SomeObject
实现AutoCloseable
您可以编写
try (final SomeObject someObject = ObjectFactory.createSomeObject()) { ... } catch (SomeException exc) { throw AppropriateToTheCallerException(exc); // or printf }
请注意隐藏的“finally”在catch
之前。 我通常会建议分离资源和exception处理。
如果您想要在try / catch / finally块中处理的ObjectFactory.createSomeObject()方法中抛出exception,这是退出try / catch / finally块后可以使用someObject的唯一方法。
使用try-catch-finally块,您可以更轻松地处理发生的任何exception。
您不能在try块中声明变量并在该块之外访问它。 所以,你在任何块之外声明它。 当您想要在finally块中释放资源时,这尤其有用。