0

该代码在 MyEclipse 上运行并返回正确的数据库集,但是一旦我将其部署到 Tomcat WebService,系统就会抛出 NullPointerException。

奇怪的是在调试期间,当系统到达

dao.getSession();

它跳到

session.close();

然后抛出“java.lang.NullPointerException”

这是示例代码:

try{
    exampleTableDAO dao = new exampleTableDAO();
    Session session = dao.getSession(); //When it reaches here
    /*****************/
    /*Other Codes*****/
    /*****************/

}catch(Exception e) {
    throw e;
} finally {
    session.close(); //Jumps here and throws error
}

经过数小时的研究,我仍然无法在互联网上找到任何提示。

4

3 回答 3

0

exampleTableDAO() 是否返回使用任何外部依赖对象构造的任何对象,该对象内部未初始化?

此外,您正在重新抛出异常,请尝试至少打印抛出的异常。

于 2013-10-29T19:13:24.773 回答
0

由于 dao.getSession() 下降到 finally 子句,而不是 Exception 的 catch 子句,因此 dao.getSession() 正在抛出 RuntimeException。在 finally 子句中,您将抛出 NullPointerException,因为您正在尝试调用 session.close() 并且 session 为 null(由于 dao.getSession 抛出了第一个 RuntimeException,它从未被初始化)。

所有这一切的根本原因可能是您与数据库的连接未在部署的应用程序中正确初始化。没有连接 == 很多 dao 异常。

于 2013-10-29T19:32:43.260 回答
0

看来您的代码正在引发某种异常。但是,不幸的是,您编写代码的方式使得当出现问题时很难找出问题所在。

首先,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.

于 2013-10-29T19:50:22.493 回答