0

I would like to know whether relying on custom exception types for flow control is considered good practice.

Let's take an example:

public void activateEmail(String token) {
    Member member = memberRepository.findByToken(token);
    if (member == null) {
        throw new InvalidTokenException("Member not found");
    }
    ...

Here, InvalidTokenException is a custom RuntimeException that is thrown if an entity is not found in database.

I use a Spring MVC exception handler as follows in order to deal with my custom exception:

@ExceptionHandler(InvalidTokenException.class)
public String invalidTokenException(InvalidTokenException e, HttpServletRequest request, HttpSession session, Locale locale) {
    FlashMap outputFlashMap = RequestContextUtils.getOutputFlashMap(request);
    if (outputFlashMap != null) {
      outputFlashMap.put("message", messageSource.getMessage("controller.preference.invalid_token_member_not_found", null, locale));
    }
     return "redirect:/signin";
    }

What are the pros and cons of such a usage of my custom exceptions?

balteo
  • 20,469
  • 52
  • 196
  • 362
  • 1
    See this questions: http://stackoverflow.com/questions/729379/why-not-use-exceptions-as-regular-flow-of-control http://stackoverflow.com/questions/1546514/java-exceptions-as-control-flow – Alberto Zaccagni Sep 02 '13 at 07:33
  • Thanks. However, my question also relates to usage of **custom exception types** as opposed to **JDK/Framework exception types**. – balteo Sep 02 '13 at 07:39
  • The reasons are the same as with regular Java exceptions. – LaurentG Sep 02 '13 at 08:22
  • 1
    You need to accept that exceptions *are* a form of flow control. There's nothing wrong with defining your own exceptions, and nothing wrong with throwing or catching them either. I wouldn't have them extend RuntimeException, however. – user207421 Sep 02 '13 at 10:25
  • @EJP Thanks for your reply. I am curious to know why you wouldn't have them extend RuntimeException? – balteo Sep 07 '13 at 19:03

0 Answers0