要檢查服務器關閉或網絡無法運行時發生的情況,我停止了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