【发布时间】:2017-09-10 11:22:58
【问题描述】:
我正在尝试捕获 SQL 异常。我有三层,
- Controller 2. Impl class 3. DAO(流程中也有一个接口,在高级别上,我将其作为 3 个级别进行描述)。
控制器
try {
// Call interface which in turn will call Impl
} catch (MyException e) {
logger.debug(e);
} catch(Exception e) {
logger.debug(e);
}
return null;
实施
try {
purchaseDto = purDAO.createPurchase(clientId);
} catch(MyException e) { --> It should catch here, as I'm throwing MyException in DAO
throw e;
}catch(Exception e) { --> DAO Exception is being catch here
throw e;
}
DAO
try {
// My business logic goes here
} catch (SQLException e) {
throw new MyException (e.getErrorCode(), e.getMessage()); --> It is catching here, from here it should go back to Impl catch block of MyException
} catch (Exception e) {
e.printStackTrace();
} finally {
pt.close();
try{
if (con != null)
con.close();
} catch (SQLException se) {
se.printStackTrace();
}
}
我的例外
public class MyException extends Exception {
/**
*
*/
private int errorCode;
private String errorDesc;
public int getErrorCode() {
return errorCode;
}
public void setErrorCode(int errorCode) {
this.errorCode = errorCode;
}
public String getErrorDesc() {
return errorDesc;
}
public void setErrorDesc(String errorDesc) {
this.errorDesc = errorDesc;
}
private static final long serialVersionUID = 1L;
public MyException () {
super();
}
public MyException (int errorCode, String errorDesc) {
super();
this.errorCode = errorCode;
this.errorDesc = errorDesc;
}
}
我在 DAO 层遇到了一个 sql 异常,如果我遇到任何 sql 异常,我将在该层抛出我的自定义异常。当它返回到 Impl 时,它会进入正常的异常捕获块(它作为空指针异常消息获取)。理想情况下,它应该转到我的自定义异常捕获,对吗?我在哪里做错了。请纠正我。
任何想法将不胜感激。
【问题讨论】:
-
我很确定 MyException 正在抛出一个异常,这就解释了为什么你得到一个 Exception 而不是 MyException。发布 MyException 的代码。
-
@dsp_user,在内部它是一个空指针异常,但我仍然在抛出我自己的异常,对吧?应该覆盖哪个?
-
NPE 不是 SqlException,因此您的代码有问题。发布其余代码。
-
@dsp_user,更新了代码,在 DAO 中,我只是添加了 finally 块。
-
请同时发布 MyException 的代码(定义)。