简体   繁体   中英

Issue in closing JDBC Connection

I have a jdbc connection which I'm trying to close but its returning a 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());

        }
    }

The stack trace is as shown:

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'

I the above code I'm checking for null condition in spite of that why is the control entering the block and trying to close connection and also giving me a 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
    }

SO in the above case when exception occurs in the constructor will the load remain null as shown in first assignment.

I could only suggest to debug your code more carefully, something like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM