<p>I know two approaches to Exception handling, lets have a look at them.</p>
<ol>
<li><p>Contract approach.</p>
<p>When a method does not do what it says it will do in the method header, it will throw an exception. Thus the method &quot;promises&quot; that it will do the operation, and if it fails for some reason, it will throw an exception.</p>
</li>
<li><p>Exceptional approach.</p>
<p>Only throw exceptions when something truly weird happens. You should not use exceptions when you can resolve the situation with normal control flow (If statements). You don't use Exceptions for control flow, as you might in the contract approach.</p>
</li>
</ol>
<p>Lets use both approaches in different cases:</p>
<p>We have a Customer class that has a method called OrderProduct.</p>
<p>contract approach:</p>
<pre><code>class Customer
{
     public void OrderProduct(Product product)
     {
           if((m_credit - product.Price) &lt; 0)
                  throw new NoCreditException(&quot;Not enough credit!&quot;);
           // do stuff 
     }
}
</code></pre>
<p>exceptional approach:</p>
<pre><code>class Customer
{
     public bool OrderProduct(Product product)
     {
          if((m_credit - product.Price) &lt; 0)
                   return false;
          // do stuff
          return true;
     }
}

if !(customer.OrderProduct(product))
            Console.WriteLine(&quot;Not enough credit!&quot;);
else
   // go on with your life
</code></pre>
<p>Here I prefer the exceptional approach, as it is not truly Exceptional that a customer has no money assuming he did not win the lottery.</p>
<p>But here is a situation I err on the contract style.</p>
<p>Exceptional:</p>
<pre><code>class CarController
{
     // returns null if car creation failed.
     public Car CreateCar(string model)
     {
         // something went wrong, wrong model
         return null;
     }
 }
</code></pre>
<p>When I call a method called CreateCar, I damn wel expect a Car instance instead of some lousy null pointer, which can ravage my running code a dozen lines later. Thus I prefer contract to this one:</p>
<pre><code>class CarController
{
     
     public Car CreateCar(string model)
     {
         // something went wrong, wrong model
         throw new CarModelNotKnownException(&quot;Model unkown&quot;);

         return new Car();
     }
 }
</code></pre>
<p>Which do style do you use? What do you think is best general approach to Exceptions?</p>

[{'answer_id': 26395, 'author': 'Vaibhav', 'author_id': 380, 'author_profile': 'https://Stackoverflow.com/users/380', 'pm_score': 0, 'selected': False, 'text': '<p>I believe that if you are building a class which will be used by an external program (or will be reused by other programs) then you should use the contract approach. A good example of this is an API of any kind.</p>\n'}, {'answer_id': 26401, 'author': 'Jorge Córdoba', 'author_id': 2695, 'author_profile': 'https://Stackoverflow.com/users/2695', 'pm_score': 1, 'selected': False, 'text': '<p>My usual approach is to use contract to handle any kind of error due to "client" invocation, that is, due to an external error (i.e ArgumentNullException).</p>\n\n<p>Every error on the arguments is not handled. An exception is raised and the "client" is in charge of handling it. On the other hand, for internal errors always try to correct them (as if you can\'t get a database connection for some reason) and only if you can\'t handle it reraise the exception.</p>\n\n<p>It\'s important to keep in mind that most unhandled exception at such level will not be able to be handled by the client anyway so they will just probably go up to the most general exception handler, so if such an exception occurs you are probably FUBAR anyway.</p>\n'}, {'answer_id': 26403, 'author': 'Kristopher Johnson', 'author_id': 1175, 'author_profile': 'https://Stackoverflow.com/users/1175', 'pm_score': 4, 'selected': True, 'text': '<p>I favor what you call the "contract" approach.  Returning nulls or other special values to indicate errors isn\'t necessary in a language that supports exceptions.  I find it much easier to understand code when it doesn\'t have a bunch of "if (result == NULL)" or "if (result == -1)" clauses mixed in with what could be very simple, straightforward logic.</p>\n'}, {'answer_id': 26548, 'author': 'Frank Krueger', 'author_id': 338, 'author_profile': 'https://Stackoverflow.com/users/338', 'pm_score': 0, 'selected': False, 'text': '<p>If you are actually interested in exceptions and want to think about how to use them to construct robust systems, consider reading <a href="http://www.erlang.org/download/armstrong_thesis_2003.pdf" rel="nofollow noreferrer">Making reliable distributed systems in the presence of software errors</a>.</p>\n'}, {'answer_id': 7517569, 'author': 'supercat', 'author_id': 363751, 'author_profile': 'https://Stackoverflow.com/users/363751', 'pm_score': 0, 'selected': False, 'text': "<p>Both approaches are right.  What that means is that a contract should be written in such a way as to specify for all cases that are not truly exceptional a behavior that does not require throwing an exception.</p>\n\n<p>Note that some situations may or may not be exceptional based upon what the caller of the code is expecting.  If the caller is expecting that a dictionary will contain a certain item, and absence of that item would indicate a severe problem, then failure to find the item is an exceptional condition and should cause an exception to be thrown.  If, however, the caller doesn't really know if an item exists, and is equally prepared to handle its presence or its absence, then absence of the item would be an expected condition and should not cause an exception.  The best way to handle such variations in caller expectation is to have a contract specify two methods: a DoSomething method and a TryDoSomething method, e.g.</p>\n\n<pre>\nTValue GetValue(TKey Key);\nbool TryGetValue(TKey Key, ref TValue value);\n</pre>\n\n<p>Note that, while the standard 'try' pattern is as illustrated above, some alternatives may also be helpful if one is designing an interface which produces items:</p>\n\n<pre>\n // In case of failure, set ok false and return default&lt;TValue&gt;.\nTValue TryGetResult(ref bool ok, TParam param);\n// In case of failure, indicate particular problem in GetKeyErrorInfo\n// and return default&lt;TValue&gt;.\nTValue TryGetResult(ref GetKeyErrorInfo errorInfo, ref TParam param);\n</pre>\n\n<p>Note that using something like the normal TryGetResult pattern within an interface will make the interface invariant with respect to the result type; using one of the patterns above will allow the interface to be covariant with respect to the result type.  Also, it will allow the result to be used in a 'var' declaration:</p>\n\n<pre>\n  var myThingResult = myThing.TryGetSomeValue(ref ok, whatever);\n  if (ok) { do_whatever }\n</pre>\n\n<p>Not quite the standard approach, but in some cases the advantages may justify it.</p>\n"}]
['https://Stackoverflow.com/questions/26383', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']