Exception Handlers

Warning.  Rant coming…

I was working on a project last week that included code that looked sort of like this:

public bool SomeMethod()
{
    try
    {
        // do some lengthy, involved, *critical* process that, 
        // if it fails, will cause the rest of the application to fail *forever*
        // as it leaves a required, persisted resource in a corrupted state
    }
    catch
    {
        return false;
    }
}

public void SomeOtherMethod()
{
    SomeMethod();
}
Of course, when I was debugging an issue in this application, SomeMethod was failing, yet I had no idea because the author of the code decided to not only throw away the exception that was being thrown, but not bother to check the return value of SomeMethod after it was called.

So here comes the rant.


Stop it!  Stop doing this!  Stop catching exceptions and either doing nothing with them, or throwing them away!  It’s an exception handler!  If you’re not going to handle the exception, don’t catch it!


I see code that does this way too much,  My other favorite is:


public void SomeMethod()
{
    try
    {
        // big code
    }
    catch
    {
    }
}

An empty exception handler.  Sure, let’s run 500 lines of code in a try block and then, if an error occurs, let’s not tell anyone.  I bet the people that write these had parents that yelled at them all the time.  In their adult life, they fear the wrath of an authority figure if an error were to occur, so they just throw away the error.


So what’s my point in all this?  If I can just get one person to not write a useless try/catch block, I’ll be happy.  Look at your code.  Look at your try/catch blocks.  If you’re not doing something important with the exception you’ve caught in your catch block, or you’re throwing away the information altogether, please fix it.  Thanks.


Leave a Reply

Your email address will not be published. Required fields are marked *


*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>