开发者

How to catch a "java.net.ConnectException: Connection refused: connect" exception

To check what happens when the server is down or the network is not working I stopped Apache and MySQL services and ran my code.

I got following error:

java.net.ConnectException: Connection refused: connect

how can I catch this exception in code?

I've tried this:

public static Connection getCon(){
  Connection con=null;


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

  catch(Exception e){
    System.out.println(e.getMessage());
    if(e.getCause() instanceof SQLException){
      JOptionPane.showMessageDialog(null, "Connection refused!");
    }                   
  }
  return con;
}

And also this

 public static Connection getCon(){
   Connection con=null;

   try{
     Class.forName("com.mysql.jdbc.Driver").newInstance();
     con=DriverManager.getConnection(
         "jdbc:mysql://localhost:3306/zo开发者_StackOverflow中文版matocrm","root","");
   }

   catch(Exception e){
     System.out.println(e.getMessage());
     if(e.getCause() instanceof ConnectException){
       JOptionPane.showMessageDialog(null, "Connection refused!");
     }                   
   }
   return con;
 }

Also I've used the connection to do data exchange with my xampp localhost sever and then tried with stopping xamp and still getting the above exception.

How do I have my code catch the exception completely?


  1. Don't check the cause, but the exception itself
  2. Catch only the kind of exception you need to catch

With that in mind:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜