为了检查服务器故障或网络不工作时会发生什么,我停止了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本地主机服务器进行数据交换,然后尝试停止xamp,但仍然得到上述异常。
如何让我的代码完全捕获异常?
发布于 2011-08-30 13:25:28
所需的异常类型
考虑到这一点:
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;
}https://stackoverflow.com/questions/7243784
复制相似问题