要检查服务器关闭或网络无法运行时发生的情况,我停止了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尝试和仍然得到上述例外。
我如何让我的代码完全捕获异常?
短期建议我如何检查连接是否正常,而我的代码正在运行!!! – srijan
你期望什么?你的代码*明确地*输出消息,所以你得到消息。还要注意,你的方法在失败时会简单地返回'null',这将简单地延迟问题并在稍后抛出'NullPointerException'。当它无法连接到数据库时,你真的希望你的代码做什么? –
我想要一个弹出,当这个异常抛出......这没有发生!代码nt正常工作!!! ...是的,我想知道它不能连接到数据库时! – srijan