异常处理和流程

时间:2014-10-15 21:06:05

标签: java

我有这个方法,对于我正在使用的sql查询和特定调查,查询不返回任何行。所以'问题'应该是空的并且应该抛出EmptyResultDataAccessException(我验证了logger.warn(msg)在我的用例中执行。)然后应该在以下方法中捕获此异常。

    private void addSurveyQuestions(Survey survey)
        throws CustomException, DataAccessException {

    StringBuilder sql = new StringBuilder();

    //Build some sql query

    List<SurveyQuestion> questions =
            getJdbcTemplate().query(sql.toString(), new Object[] { survey.getQuestionnaireKey() },
                    new SurveyQuestionRowMapper());

    // This should never happen, but just in case
    if (questions == null || questions.size() == 0) {
        String msg = "Expected at least 1 question for survey " + survey.getQuestionnaireKey();
        logger.warn(msg);
        throw new EmptyResultDataAccessException(msg, 1);
    }

    // Loop through all the questions - populate the multiple choice answers and add questions to survey
    for (SurveyQuestion q : questions) {
            //some stuff
        }
        survey.addSurveyQuestion(q);
    }
}

在我的用例的方法中,sql查询将返回一行,因此'survey'不为null,并且将执行addSurveyQuestions(survey),这将抛出EmptyResultDataAccessException。然后应该捕获此方法并返回null。但是我从未见过logger.info(“没有调查调查”+ surveyKey);正在执行,并且正在返回一个调查对象,其中返回了一个空的surveyQuestions列表(已启用信息级别日志记录)。

public Survey getSurvey(Long surveyKey) throws CustomException {

    StringBuilder sql = new StringBuilder();

    //some sql query

    try {
        // Get top level container object
        Survey survey =
                getJdbcTemplate().queryForObject(sql.toString(), new Object[] {surveyKey },
                        new SurveyRowMapper());

        // Add the questions and answers
        if (survey != null) {
            addSurveyQuestions(survey);
        }

        return survey;

    } catch (EmptyResultDataAccessException empty) {

        // This is ok,no surveys.
        logger.info("No surveys  for survey " + surveyKey);
        return null;

    } catch (DataAccessException dae) {
        String msg = "some message " + surveyKey;
        logger.error(msg);
        throw new CustomException(msg + ", Exception: " + dae.getMessage(), dae);
    }
}

为什么没有捕获EmptyResultDataAccessException的任何想法?

0 个答案:

没有答案