1

我从控制器抛出异常,如下所示

try {
    if (formValidationResult.size() > 0) {
        validationResults.put(errorMsg, formValidationResult);
    }
} catch (Exception exception) {
    LOGGER.error("Error while performing validation in FormController -->"
                    + exception.getMessage());
    throw new ServiceException(exception.getMessage());
}
if (validationResults.size() > 0) {
    throw new ValidationFailureException(validationResults,"Validation Error");
}

在这里我收到一个验证错误;

com.ge.dbt.common.exception.ValidationFailureException:验证错误

我可以包括一个 catch 块来捕捉ValidationFailureException这里吗?

4

2 回答 2

5

是 Java 允许。您可以使用 try catch 块抛出和处理异常

   try
    {
        throw new Exception();
    }
    catch (Exception e) {
        // TODO: handle exception
    }

在这里,您在同一个块中抛出和处理异常。我不知道为什么有人愿意这样做。

更好的方法是让您的方法定义为throws ValidationFailureException并处理调用此代码的函数的异常。

于 2012-10-03T12:31:24.627 回答
1

Assuming that validationResult and formValidationResult are collections, I don't see why there is a need to enclose the call to the size and put methods in a try catch block? What exception are you expecting anyway while checking the size of these collections or inserting a new value anyway?

I can't give you the code because I am typing from my phone but this is what you can do :

  1. Indicate that the method containing your code throws a ValidationFailureException in the method signature.

  2. Remove the try catch block you have presented and remove the if block that checks whether validationResult is non empty and the code inside the if block.

  3. If formValidationResult is not empty, store the error message in validationResult and throw a ValidationFailureException.

That's it. Clean and simple. No need for any try-catch blocks and no need to separately check if validationResult is not empty before throwing a ValidationFailureException.

于 2012-10-03T19:43:51.917 回答