看来您的代码正在引发某种异常。但是,不幸的是,您编写代码的方式使得当出现问题时很难找出问题所在。
首先,finally
执行清理的块应该始终检查它们试图清理的对象是否是首先创建的。如果一个try
块尝试创建一个对象,但失败并引发异常,该finally
块仍将运行,但它无法清理从未创建的对象。
这正是您的代码中发生的事情。您收到 NullPointerException 是因为您试图在没有要关闭的会话时关闭会话。
更糟糕的是,从finally
块中抛出的异常会替换之前可能已抛出的任何异常。不管是什么都已经丢失了,现在你得到了一个 NullPointerException 。
So, before attempting to close anything in a finally
block, always check that it is not null.
Secondly, there really is no point to your catch
block. All it achieves is obscuring where the real error is coming from. I'd recommend simply deleting it.
The code fragment you have provided is unclear: it seems you might have a field named session
in addition to the local variable also named session
that you declare inside the try
block. (If you didn't have a field session
, your code won't compile because the session
local variable will be out of scope in the finally
block.)
The next step is either to use the session
field, if it exists:
try {
exampleTableDAO dao = new exampleTableDAO();
// Use field.
session = dao.getSession();
/*****************/
/*Other Codes*****/
/*****************/
} finally {
// Check if field is null, and if not, close it.
if (session != null) {
session.close();
}
}
or to use a local variable declared outside the try
block:
Session session = null;
try {
exampleTableDAO dao = new exampleTableDAO();
// Use local variable.
session = dao.getSession();
/*****************/
/*Other Codes*****/
/*****************/
} finally {
// Check if local variable is null, and if not, close it.
if (session != null) {
session.close();
}
}
Your code will be unlikely to start working now, but it should at least be giving you a better idea of what's going wrong.