首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何捕获"java.net.ConnectException: Connection :Connection“异常

如何捕获"java.net.ConnectException: Connection :Connection“异常
EN

Stack Overflow用户
提问于 2011-08-30 13:18:36
回答 1查看 11K关注 0票数 0

为了检查服务器故障或网络不工作时会发生什么,我停止了Apache和MySQL服务,并运行了我的代码。

我发现了以下错误:

java.net.ConnectException:连接被拒绝:连接

如何在代码中捕获此异常?

我试过这个:

代码语言:javascript
复制
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;
}

还有这个

代码语言:javascript
复制
 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 ConnectException){
       JOptionPane.showMessageDialog(null, "Connection refused!");
     }                   
   }
   return con;
 }

此外,我还使用连接与我的xampp本地主机服务器进行数据交换,然后尝试停止xamp,但仍然得到上述异常。

如何让我的代码完全捕获异常?

EN

回答 1

Stack Overflow用户

发布于 2011-08-30 13:25:28

  1. 不检查原因,但异常本身
  2. 只捕获捕获

所需的异常类型

考虑到这一点:

代码语言:javascript
复制
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;
}
票数 -2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/7243784

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档