【发布时间】: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