开发者

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

开发者 https://www.devze.com 2023-03-31 14:01 出处:网络
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.

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

精彩评论

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