Catch All vs. Catch Explicit…

by Mwwhited 12. May 2010 20:37

I knew I liked writing my try{} catch{} blocks to catch all exceptions instead of explicit Exceptions… but I always had a hard time explaining why.  Most of the time I would just point out that I typically write backend long life processes that must be very reliable and must avoid causing the process to fail as much as possible.  But I would like to thank Dhanji R. Prasanna from his book Dependency Injection: Design Patterns using Spring and Guice.  Giving me a great example.


    // this code was adapted from the Java example on page 159
    public void Start()
    {
        transaction.Begin();

        bool failed = false;

        try
        {
            chamber1.Fire();
            chamber2.Fire();
            chamber3.Fire();
        }
        catch (StartFailedException)
        {
            failed = true;
        }
        finally
        {
            if (failed)
                transaction.Rollback();
            else
                transaction.Commit();
        }
    }

… Now for the background of this code before I go into why I would like to point out why this is bad practice….

300px-Chernobyl_Disaster[1]The description behind this process given by Dhanji is that this code is to run a nuclear power plant.  If any of the reaction chambers fail to .Fire() then all of the chambers should abort.  (This is an example for an ACID transaction.)  Now this is great.  In his example one of the chambers is written to throw a StartFailedException when the reactor temperature is too high… perfect the exception would be caught and all the reactors would shutdown.  But let’s look at why I believe this is a failed idea.  Let’s assume that chamber2 has a fault that was not explicit caused in the .Fire() method… but was called by code called by the .Fire() method.  Maybe a sensor is off line or out of calibration.  That sensor causes the code behind the Gauge in the Chamber to throw a SensorOfflineException… 

Well…

  • chamber1.Fire() ran fine
  • chamber2.Fire() threw an unexpected error (definition of an exception)
  • chamber3.Fire() is never called.

… so what would happen…

Better hold onto your shorts, we may have just found the real cause of the Chernobyl disaster.Looks like the power plant may explode.  After all we called transaction.Commit() even though chamber2 failed to .Fire() and we never even tried to .Fire() on chamber3.

Let this nuclear melt down be a lesson for you… There are reasons to catch all exceptions… even if you want to rethrow them.  If you ever had the need to write your own personal nuclear reactor… please practice safe coding and catch all exceptions. 

Tags:

Comments

Comments are closed

Powered by BlogEngine.NET 1.5.0.7
Theme by Mads Kristensen

RecentPosts

Badges