如何完美地抛出DAO异常......有人可以帮助我。
catch块应该给出什么异常。 有人可以告诉我如何完美地完成这项工作。
public static List<Product> loadProductsAvailable() throws **//throws which exception for dao**
SQLException {
List<Product> productList = new ArrayList<>();
Connection connection = null;
ResultSet resultSet = null;
Statement statement = null;
try {
connection = ConnectionFactory.getConnection();
statement = connection.createStatement();
resultSet = statement.executeQuery(GET_ALL_PRODUCTS_SQL);
while (resultSet.next()) {
productList.add(getProductFromResultSet(resultSet));
}
} finally {
try {
if (connection != null) {
statement.close();
resultSet.close();
connection.close();
}
} catch ( **//what exception should be given here to throw dao exception** ) {
**//how to code for dao exception**
}
}
return productList;
}
答案 0 :(得分:1)
在catch中抛出异常如下:
try {
} catch(DAOException e) {
throw new DAOException(DAOException.TYPE.SQLE, e);
}
答案 1 :(得分:1)
//在例外情况下在dao包中创建以下自定义异常类 公共类DataAccessException扩展Exception {
private String exceptionMsg;
public DataAccessException(String exceptionMsg){
this.exceptionMsg = exceptionMsg;
}
public String getExceptionMsg() {
return exceptionMsg;
}
public void setExceptionMsg(String exceptionMsg) {
this.exceptionMsg = exceptionMsg;
}
}
public static List<Product> loadProductsAvailable() throws **//throws which DataAccessException {
List<Product> productList = new ArrayList<>();
Connection connection = null;
ResultSet resultSet = null;
Statement statement = null;
try {
connection = ConnectionFactory.getConnection();
statement = connection.createStatement();
resultSet = statement.executeQuery(GET_ALL_PRODUCTS_SQL);
while (resultSet.next()) {
productList.add(getProductFromResultSet(resultSet));
}
} finally {
try {
if (connection != null) {
statement.close();
resultSet.close();
connection.close();
}
} catch (DataAccessException dataAccessException ) {
throw new DataAccessException("Data base Access Exception"+dataAccessException.getMessage());
}
}
return productList;
}
答案 2 :(得分:0)
您可以为dao图层定义自定义例外,并使用它从那里投掷。您可以在该异常类中定义errorCode和errorMessage,如此
public class DaoLayerException extends RuntimeException {
private String errorMessage;
private int errorCode;
public DaoLayerException() {
}
public DaoLayerException(int code, String message) {
this.errorMessage = message;
this.errorCode = code;
}
}
然后在你的代码中使用
try {
//your code
} catch (Exception e) {
throw new DaoLayerException("yourerrorcode", e.getMessage());
}