gpt4 book ai didi

java - 关闭 JDBC 连接时出现问题

转载 作者:行者123 更新时间:2023-12-01 13:31:07 24 4
gpt4 key购买 nike

我有一个 jdbc 连接,我试图关闭它,但它返回 NullPointerException。

finally
{
try
{
if(load.dbConnection!=null)
{
load.dbConnection.close();
LOGGER.info("Connection closed successfully");
}
}
catch(Exception e)
{
LOGGER.info("Exception is closing db connection"+e.getLocalizedMessage()+" "+e.getMessage()+" "+e.toString());

}
}

堆栈跟踪如下所示:

Exception occured nullLevel [0] - File Name: 'loadData.java' Method Name: 'verifyFiles' Line Number: '896' Message: 'java.lang.Exception'
Level [1] - File Name: 'loadData.java' Method Name: '<init>' Line Number: '106' Message: 'java.lang.Exception'
Level [2] - File Name: 'loadData.java' Method Name: 'main' Line Number: '119' Message: 'java.lang.Exception'

我在上面的代码中检查 null 条件,尽管如此,为什么控件进入 block 并尝试关闭连接,并且还给了我一个 java.lang.NullPointerException。

//Initial assignment
loadData load = null;

try
{
load = new loadData(); //Here the constructor calls 3 functions and exception occurs in one of those functions.

}
catch(Exception e){....}
finally
{
//The finally code shown above
}

在上述情况下,当构造函数中发生异常时,负载将保持为空,如第一个赋值所示。

最佳答案

我只能建议更仔细地调试您的代码,如下所示:

        //Initial assignment
loadData load = null;
System.out.println("logger is a null?: " + LOGGER);
LOGGER.info("load: "+load);
try
{

load = new loadData(); //Here the constructor calls 3 functions and exception occurs in one of those functions.
LOGGER.info("load init: "+load);
}
catch(Exception e){
e.printStackTrace();
}
finally
{
LOGGER.info("finally load: "+load);
try
{
LOGGER.info("finally connection: " + load.dbConnection);
if(load.dbConnection!=null)
{
load.dbConnection.close();
LOGGER.info("Connection closed successfully");
}
}
catch(Exception e)
{
e.printStackTrace();
}
}

关于java - 关闭 JDBC 连接时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21568095/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com