Search code examples
javasqljdbcprepared-statementexecutequery

statement.executeQuery() mystery. Code not being executed, nor exception is being caught.


Providing the code and the output. Searched the internet but didn't find solution. Everything compiles and runs okay, up until "//PROBLEMATIC LINE", where execution goes directly to "//HERE" without any indication, exception or error. I have used this code with the jdbc driver for SQLServer many times and works fine, what am I possibly missing here? In the same application I am also using this code with mySql jdbc driver and again, works fine. Just in this piece of code it is that there is a problem. Obviously I am using java.sql.*; .

try {
        Class.forName(driver);
        setResponse("Failure. 1");
        connectionTest = DriverManager.getConnection(url, username, password);
        setResponse("Failure. 2");
        String query = "SELECT TOP (1) [id] FROM "+ table + ";";
        PreparedStatement statement = connectionTest.prepareStatement(query);
        setResponse("Failure. 3");
        System.out.println(statement);
        ResultSet resultset = statement.executeQuery();  //PROBLEMATIC LINE
        System.out.println("DOES NOT EVEN PRINT THIS");
        setResponse("Failure. 4");
        if (resultset.first()) setResponse("Success.");
        else setResponse("Failure. 5");
        System.out.println("Query success: ");  
        setResponse("Failure. 6");
    }
    catch (Exception e) {
        e.printStackTrace();
    }
    finally {
        try {
            connectionTest.close();  //HERE
            return getResponse();
        }
        catch (Exception e) {
            e.printStackTrace();
            return getResponse();
        }
    }

Output:

------------------------------------
-------------DATABASES--------------
------------------------------------
SQLServerPreparedStatement:1
Failure. 3
------------------------------------
----------TESTS COMPLETED-----------
------------------------------------

Solution

  • When an exception is thrown, the try block will exit. When the try block exits, the finally block will be executed. Since you have return statements in your finally block, you will never get to the catch block.

    Don't return in your finally block. Then the stacktrace will get printed and you can deal with the exception.