Bug #30968 CommunicationsException not thrown
Submitted: 12 Sep 2007 9:08 Modified: 12 Sep 2007 11:18
Reporter: Bogdan Enache Email Updates:
Status: Closed Impact on me:
None 
Category:Connector / J Severity:S1 (Critical)
Version:5.0.7 OS:Windows (XP Professional SP2)
Assigned to: CPU Architecture:Any
Tags: CommunicationsException, ConnectException

[12 Sep 2007 9:08] Bogdan Enache
Description:
When trying to connect to a local MySQL 5.0 server that is not running (its instance has been shutdown), I get some errors (obviously):

com.mysql.jdbc.CommunicationsException: Communications link failure due to underlying exception: 

** BEGIN NESTED EXCEPTION ** 

java.net.ConnectException
MESSAGE: Connection refused: connect

STACKTRACE:

java.net.ConnectException: Connection refused: connect
[...................................................................]
Etc.

The problem is that I can't see any way to catch that Exception or test if the connection is valid. None of the things I tried work. The manual for Connector/J does not say anything about this.

How to repeat:
Connection con = null;
        try{
            //Get a connection
            Class.forName("com.mysql.jdbc.Driver");
            con = DriverManager.getConnection("jdbc:mysql://localhost:3306", "root", "pass");
        } catch(ClassNotFoundException cnfe){
            JOptionPane.showMessageDialog(null, "Driver not found", "Driver not found", JOptionPane.ERROR_MESSAGE);
            System.exit(0);
        } catch(SQLException se){
            JOptionPane.showMessageDialog(null, "SQL Exception", "SQL Exception", JOptionPane.ERROR_MESSAGE);
            System.exit(0);
        } finally{
            try{
                //Check if the connection is valid
                if(con == null || con.isClosed() || !con.isValid(0)){
                    JOptionPane.showMessageDialog(null, "Invalid connection", "Invalid connection", JOptionPane.ERROR_MESSAGE);
                    System.exit(0);
                }
                Statement stmt = con.createStatement();
                ResultSet rs = stmt.executeQuery("SELECT 1;");
            } catch(SQLException se){
                JOptionPane.showMessageDialog(null, "SQL Exception", "SQL Exception", JOptionPane.ERROR_MESSAGE);
                System.exit(0);
            }
        }
        return con;
    }

Suggested fix:
The getConnection method should throw the CommunicationsException, or some other Exception maybe.
[12 Sep 2007 11:18] Bogdan Enache
Sorry, broken JRE. Closing the bug myself.