我看到很多像这样的代码:
SomeObject someObject = null;
try{
someObject = ObjectFactory.createSomeObject();
...
Run Code Online (Sandbox Code Playgroud)
与此相比,这样做有什么好处:
SomeObject someObject = ObjectFactory.createSomeObject();
Run Code Online (Sandbox Code Playgroud)
这是一个常用的习惯用法,你必须用null初始化连接,因为Java只支持类成员的初始化,在这个范围内你必须用它初始化它null,因为ConnectionFactory.create()也许会引发异常.
您可以使用它来扩展变量的范围并在以后使用它,例如关闭连接句柄.
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()
}
}
Run Code Online (Sandbox Code Playgroud)
如果初始化catch块中的连接,则finally块或以下代码不可见.
| 归档时间: |
|
| 查看次数: |
2457 次 |
| 最近记录: |