2011-08-30 566 views
0

要检查服务器关闭或网络无法运行时发生的情况,我停止了Apache和MySQL服务并运行我的代码。
我得到了以下错误:如何捕捉“java.net.ConnectException:连接被拒绝:连接”异常

java.net.ConnectException: Connection refused: connect

我怎么能捕获此异常的代码?

我已经试过这样:

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本地主机服务器,然后用停止XAMP尝试和仍然得到上述例外。

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

+0

短期建议我如何检查连接是否正常,而我的代码正在运行!!! – srijan

+2

你期望什么?你的代码*明确地*输出消息,所以你得到消息。还要注意,你的方法在失败时会简单地返回'null',这将简单地延迟问题并在稍后抛出'NullPointerException'。当它无法连接到数据库时,你真的希望你的代码做什么? –

+0

我想要一个弹出,当这个异常抛出......这没有发生!代码nt正常工作!!! ...是的,我想知道它不能连接到数据库时! – srijan

回答

-2
  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; 
} 
+0

里面的代码尝试也抛出SQLException ...如何保持跟踪! – srijan

+3

**实际上**''ConnectException'永远不会被抛出该代码!我怀疑''ConnectException'是*原因*引发'SQLException'! –

相关问题