srijan
srijan

Reputation: 31

syntax warning showing: exception is never thrown in body of try statement

public class SetupConnection{

  public static Statement setCon(){
    Connection con=null;
    Statement st=null;                

    try{
      Class.forName("com.mysql.jdbc.Driver").newInstance();
      con=DriverManager.getConnection(
                        "jdbc:mysql://localhost:3306/zomatocrm","root","");
      st = con.createStatement();
    }
    catch(ConnectException err){
      JOptionPane.showMessageDialog(null, "Connection refused!!!");
      System.out.println(err.getMessage());
    }            
    catch(Exception e){
      System.out.println(e.getMessage());                   
    }   
    return st;
  }

The warning:

exception is never thrown in body of try statement

is coming up at the catch(ConnectException){ line.

Upvotes: 0

Views: 5276

Answers (3)

beny23
beny23

Reputation: 35018

Note, if the connection to the database fails due to network problems, you'll still only get a SQLException, so catching that would be better and if you want to determine whether there was a networking problem you could check the SQLState (according to the manual):

try {
    ...
} catch (SQLException sqle) {
    if ("08S01".equals(sqle.getSQLState())) {
        JOptionPane.showMessageDialog(null, "Connection refused (or networking problem)!!!");
        System.out.println(err.getMessage());
    }
}

Also (as a general point, not related to this error), your method creates a connection (con object), but no reference to it is ever returned, so how are you closing the connection? Not closing a connection can lead to a connection leak, which will cause you problems.

Upvotes: 1

razlebe
razlebe

Reputation: 7144

None of the code in your try block:

Class.forName("com.mysql.jdbc.Driver").newInstance();     
con=DriverManager.getConnection(
    "jdbc:mysql://localhost:3306/zomatocrm","root","");
st = con.createStatement();

...can ever throw a ConnectException. Therefore the compiler is warning you that this catch clause:

catch(ConnectException err){
    JOptionPane.showMessageDialog(null, "Connection refused!!!");
    System.out.println(err.getMessage());
} 

is redundant. If you remove it, the warning will go away.

Upvotes: 2

king_nak
king_nak

Reputation: 11513

getConnection and createStatement throw SQLException, which is caught in your second catch block. ConnectException is never thrown...

Upvotes: 1

Related Questions