title: Java flow control by throwing exceptions
body: <p>I have a question that is bothering me for a while about the preferable flow control method.</p>
  
  <p>I often encounter a situation, where I have to decide what to do based on return value from a method which is <code>null</code> or <code>not null</code></p>
  
  <p>So I have two options which I know about, how to deal with it:</p>
  
  <p>Check for null:</p>
  
  <pre><code>public class BasedOnNullFlowControl {
  
      public String process(String login) {
          String redirectUri = getRedirectUri(login);
          if (redirectUri != null) {
              return redirectUri;
          } else {
              return "Your login is taken";
          }
      }
  
      private String getRedirectUri(String login) {
          Optional&lt;Login&gt; loginFromDb = checkLoginExists(login);
          if (loginFromDb.isPresent()) {
              return null;
          } else {
              return "some-redirect-url";
          }
      }
  
      private Optional&lt;Login&gt; checkLoginExists(String login) {
          return Optional.empty(); //assume this value comes from some API
      }
  
      private class Login {}
  }
  </code></pre>
  
  <p>Or interrupt the flow with exception:</p>
  
  <pre><code>public class ExceptionFlowControl {
  
      public String process(String login) {
          return getRedirectUri(login);
      }
  
      private String getRedirectUri(String login) {
          Optional&lt;Login&gt; loginFromDb = checkLoginExists(login);
  
          loginFromDb.ifPresent(l -&gt; {
              throw new LoginExistsException();
          });
          return "some-redirect-url";
      }
  
      private Optional&lt;Login&gt; checkLoginExists(String login) {
          return Optional.empty();
      }
  
      private class LoginExistsException extends RuntimeException {
      }
  
      private class Login {}
  }
  </code></pre>
  
  <p>I know, that exceptions should be used only in exceptional situations, but my situation is not exceptional and still second solution looks better for me, because I can add some exception handler (like in Spring) and translate it to some nice Http status code in the end. The controller method <code>process</code> is not contaminated with dozens null checks.</p>
  
  <p>Could you smart people please advise which one solution should be used? Or maybe there is a third one?</p>