【问题标题】:How to catch a "java.net.ConnectException: Connection refused: connect" exception如何捕获“java.net.ConnectException:连接被拒绝:连接”异常
【发布时间】:2011-08-30 13:18:36
【问题描述】:

为了检查服务器关闭或网络不工作时会发生什么,我停止了 Apache 和 MySQL 服务并运行了我的代码。
我收到以下错误:

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

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

我试过了:

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;
}

还有这个

 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 localhost 服务器进行数据交换,然后尝试停止 xamp 并仍然出现上述异常。

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

【问题讨论】:

  • 简而言之,建议我如何在我的代码运行时检查连接是否良好!!!..
  • 你期待什么?您的代码显式打印消息,因此您收到消息。另请注意,您的方法在失败时将简单地返回null,这只会延迟问题并稍后抛出NullPointerException。当无法连接到数据库时,您实际上希望您的代码做什么?
  • 我想在抛出这个异常时弹出一个窗口......这不会发生!代码没有按预期工作!!!...是的,我想知道它何时无法连接到数据库!!
  • @srijan:请在多余的感叹号和句号上放轻松,并学习使用完整的单词。为什么不简单地在所有SQLExceptions 上显示弹出窗口? 为什么您无法连接到数据库真的很重要吗?另外:您希望在显示消息后 发生什么?还有一些代码在等待它Connection

标签: java mysql exception-handling


【解决方案1】:
  1. 不查原因,查异常本身
  2. 只捕获您需要捕获的异常类型

考虑到这一点:

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;
}

【讨论】:

  • try 中的代码也会抛出 SQLException...如何跟踪它!!
  • 实际上 ConnectException 永远不会在该代码中抛出!我怀疑SQLException 被抛出ConnectException原因
猜你喜欢
  • 2014-10-13
  • 1970-01-01
  • 1970-01-01
  • 2017-08-10
  • 2023-03-21
  • 2015-05-18
  • 2018-06-10
  • 1970-01-01
相关资源
最近更新 更多