关闭JDBC连接时出现问题

时间:2014-02-05 03:29:40

标签: java jdbc

我有一个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条件,尽管为什么控件进入块并尝试关闭连接并且还给我一个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
    }

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

1 个答案:

答案 0 :(得分:1)

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

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