To check what happens when the server is down or the network is not working I stopped Apache and MySQL services and ran my code.
I got following error:java.net.ConnectException: Connection refused: connect
how can I catch this exception in code?
I've tried this:
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;
}
And also this
public static Connection getCon(){
Connection con=null;
try{
Class.forName("com.mysql.jdbc.Driver").newInstance();
con=DriverManager.getConnection(
"jdbc:mysql://localhost:3306/zo开发者_StackOverflow中文版matocrm","root","");
}
catch(Exception e){
System.out.println(e.getMessage());
if(e.getCause() instanceof ConnectException){
JOptionPane.showMessageDialog(null, "Connection refused!");
}
}
return con;
}
Also I've used the connection to do data exchange with my xampp localhost sever and then tried with stopping xamp and still getting the above exception.
How do I have my code catch the exception completely?
- Don't check the cause, but the exception itself
- Catch only the kind of exception you need to catch
With that in mind:
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;
}
精彩评论