简体   繁体   English

Java中的空赋值有何优势?

[英]What is the advantage of null assignment in Java?

I see a lot of code like this: 我看到很多这样的代码:

SomeObject someObject = null;

try{

   someObject = ObjectFactory.createSomeObject();
   ...

What is the advantage of doing this compared to this: 与此相比,这样做的好处是什么:

SomeObject someObject = ObjectFactory.createSomeObject();

This is an common used idiom, you have to initialize the connection with null, because Java only support initialization for class members, in this scope you have to initialize it with null , because ConnectionFactory.create() maybe also throws an exception. 这是一个常用的习惯用法,您必须使用null初始化连接,因为Java仅支持初始化类成员,在这种情况下,您必须使用null初始化它,因为ConnectionFactory.create()可能还会引发异常。

You use this to widen the scope of your variable and use it later, for example to close your connection handle. 您可以使用它来扩大变量的范围,并在以后使用它,例如关闭连接句柄。

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

If you initialize the connection within the catch block it is not visible for the finally block or the following code. 如果在catch块中初始化连接,则对于finally块或以下代码不可见。

It's a common pattern when creating objects that need to be destroyed or resources that need to be disposed of. 在创建需要销毁的对象或需要处置的资源时,这是一种常见的模式。 For instance, with database connections: 例如,使用数据库连接:

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

If you declare the objects inside of the try block then they cannot be referenced inside the finally since it has a different scope. 如果在try块内声明对象,则无法在finally内引用它们,因为它具有不同的作用域。 The declarations need to be outside the try but the assignments need to be inside so that exceptions during initialization can be caught. 声明需要在try之外,但分配必须在try内,以便可以捕获初始化期间的异常。

The close() calls must be done inside of a finally block to ensure that the database resources are freed whether or not the database calls succeed. 必须在finally块内完成close()调用,以确保无论数据库调用是否成功,都释放数据库资源。

它可能与someObject变量的范围(可见性)相关,因此该变量可以稍后在try-catch -block之外使用。

It's an ill-advised little dance people play with null s in an attempt to merge a try - finally with a try - catch . 这是一个不明智的小舞蹈,人们尝试将null与s结合在一起,以尝试将try - finallytry - catch合并。 It's frequently accompanied by bugs (NPE, not closing everything in the unhappy case, releasing resources not acquired, etc. - people are so inventive with bugs in sloppy code). 它经常伴随着错误(NPE,在不满意的情况下不关闭所有内容,释放未获得的资源,等等-人们对具有松散代码的错误非常有创造力)。 Much better to split the two different forms of try , possibly into different methods. 将两种不同形式的try拆分成可能更好的方法可能更好。 Unlike the try - catch - finally combo, the finally should be within the catch . try - catch - finally组合不同, finally应该在catch

try {
    final SomeObject someObject = ObjectFactory.createSomeObject();
    try {
        ...
    } finally {
        someObject.dispose();
    }
} catch (SomeException exc) {
    throw AppropriateToTheCallerException(exc);
    // or printf
}

In JDK7, assuming SomeObject implements AutoCloseable you can write 在JDK7中,假设SomeObject实现了AutoCloseable ,则可以编写

try (final SomeObject someObject = ObjectFactory.createSomeObject()) {
    ...
} catch (SomeException exc) {
    throw AppropriateToTheCallerException(exc);
    // or printf
}

Note that the hidden "finally" goes before the catch . 请注意,隐藏的“最终”位于catch之前。 I would generally suggest separating resource and exception handling. 我通常建议将资源和异常处理分开。

如果要在try / catch / finally块中处理的ObjectFactory.createSomeObject()方法中可能引发异常,则这是退出try / catch / finally块后可以使用someObject的唯一方法。

Using the try-catch-finally blocks, you can more easily handle any exceptions that occur. 使用try-catch-finally块,您可以更轻松地处理发生的任何异常。

You can't declare the variable inside the try block and access it outside of that block. 您不能在try块内声明变量并在该块外访问它。 So, you declare it outside any block. 因此,您可以在任何块之外声明它。 This is particularly helpful when you want to release resources in a finally block. 当您要在finally块中释放资源时,这特别有用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM