title: How should I handle expected errors? eg. "username already exists"
body: <p>I am struggling to understand how I should design the error handling parts of my code. I recently asked a similar question about how I should go about <a href="https://stackoverflow.com/questions/2790540/is-it-bad-to-throw-exceptions-to-return-server-errors-eg-404-page-not-found">returning server error codes to the user, eg. 404 errors</a>. I learnt that I should handle the error from within the current part of the application; seem's simple enough.</p>
  
  <p>However, what should I do when I can't handle the error from the current link in the chain? For example, I may have a class that is used to manage authentication. One of it's methods could be <code>createUser($username, $password)</code>. <strong><em>Edit:</strong> This method will return a user id or user object.</em> Within that function, I need to determine if the username already exists. If this is true, how should I alert the calling code about this? Returning null instead of a user object is one way. But how do I then know what caused the error?</p>
  
  <p><strong>How should I handle errors in such a way that calling code can easily find out what caused the error? Is there a design pattern commonly used for this kind of situation?</strong></p>
  
  <p><strong>Edit:</strong> I forgot to mention: I am using PHP.</p>
  
  <hr>
  
  <p><strong>Solved:</strong> While many people argue that exceptions should not be used in this situation, I have come to the conclusion that it is the best solution.</p>
  
  <p>Firstly, there is no simple, elegant alternative to exceptions. (I recon that it is not possible without a system built into the language... exceptions are already built in.)</p>
  
  <p>Secondly, in response to the "exceptions should only be used for exceptional situations, and this is not one" argument: <a href="http://wolfie.github.com/2010/03/14/exceptional-heresy.html" rel="nofollow noreferrer"><em>"When I call getFoo(), I actually expect to get a Foo. If I don't get it, it's by definition an exceptional event."</em></a> (via, <a href="https://stackoverflow.com/questions/2790540/#comment-2826998">pkainulainen</a>)</p>