2014-02-20 50 views
3

我想在Java中使用MySQL來捕捉特定的異常。但是,它正在運行catch (SQLException ex)而不是我想要的那個。發現錯誤的異常

catch (MySQLIntegrityConstraintViolationException ex) { 
} 
catch (SQLException ex) { 
} 

收到以下錯誤,我希望它運行catch (MySQLIntegrityConstraintViolationException ex)功能。

11:12:06 AM DAO.UserDAO createUser 
SEVERE: null 
com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Duplicate entry 'idjaisjddiaij123ij' for key 'udid' 

爲什麼運行catch (SQLException ex)代替catch (MySQLIntegrityConstraintViolationException ex)

+0

你可以添加ex.printStackTrace();在每個catcha裏面並粘貼異常? –

+0

它有沒有出現在'.getCause()'中? – fge

回答

2

是的MySQL總是在執行方法中捕獲SQLException。你所要做的就是趕在你的執行方法的SQLException,他們因此在調用execute方法外方法拋出新MySQLIntegrityConstraintViolationException

public void executeQuery() { 
    try { 
     // code 
     rs = pstmt.executeQuery(); 
} catch (SQLException ex) { 
    throw new MySQLIntegrityConstraintViolationException(ex); 
} 

,它應該只捕獲了MySQLIntegrityConstraintViolationException

catch (MySQLIntegrityConstraintViolationException ex) { 
    //handle ex 
} 
+0

即使我遇到過這種情況,薩拉所說的也是我的做法。不知何故,在執行過程中,如果你知道你正在尋找什麼異常,然後從SQLException的catch塊中拋出它,最終會得到SQLException,這是正確的方法。 –

1

我建議使用ex instanceof MySQLIntegrityConstraintViolationException以確保沒有其他異常作爲MySQLIntegrityConstraintViolationException拋出,因爲可能由於許多不同原因拋出SQLException。

0

請輸入

com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException; 

我測試,它會工作。

+2

如果沒有導入這個類,代碼如何編譯? – J0e3gan

4

確保您使用正確的名稱空間。對於我來說,一個形象附加作品像魅力。

Correct namespace