tags:

views:

156

answers:

5

I have many portions in code where I do

try
{
    // not so important code, but don't want this to affect anything else
}

catch
{
}

Is using this considered as a bad practice?

Try(() => 
{
});

void Try(Action a)
{
    try
    {
        a();
    }
    catch
    {
        // ignore.
    }
}
+3  A: 

If you truly don't care about what the "unimportant" code does then I would say it's fine. Using the lambda makes it more readable, but it can also hide the fact that you're "swallowing" the exception. Personally I like to leave it in there, so it's explicit and put a comment into the empty catch block, explaining why it's OK to ignore any errors. Of course, the comment is specific to each situation.

Evgeny
It might improve understanding if Sandeep renamed the `Action` to IgnoreException, or something. Then at least when people read the code know what's happening.
Matt Ellen
+3  A: 

Swallowing exceptions is generally considered bad practice, as it makes maintenance of the program difficult.

However, moving all exception handling to a central location may be a step in the right direction, as it allows you to at least log the exceptions in the future without going through your entire code base.
As long as it is limited to places where you really don't care exceptions occur, it can be a positive change.

Kobi
+1 - I would also suggest that change the name Try to something like RunAndIgnoreException.
VinayC
I use mainly use this for logging. try { //log } catch {}
Sandeep
A: 

the void Try (Action a) is rather obscure the other approach is easier to read

camilin87
+5  A: 

Of course you could always add an exception handler:

void Try(Action a, Action<Exception> onErr)
{
    try
    {
        a();
    }
    catch (Exception e)
    {
        onErr(e);
    }
}

Then you'd have:

Try( 
    ()=> { /* do something */ }
    e => { } );

You could have a standard empty hander

static void IgnoreError(Exception e) 
{
    #if DEBUG
    throw e;
    #end if
}

Try( 
    ()=> { /* do something */ }
    IgnoreError );

I don't think that's bad as such, but it is very non-standard - your code will be confusing and I don't think it adds anything. It's interesting to consider, but I think your code will end up very confusing.

Also, while there are circumstances where you might want to ignore an exception you don't really want to make it easier to do so regularly.

Keith
won't that hose the call stack as everything will come out of IgnoreError.
Conrad Frix
yes, but at least you'll get something. You could add the conditional throw the the `Try` method's catch and then you'd preserve the stack. I still would recommend against actually doing this.
Keith
A: 

Both the standard empty catch or using a lambda to do the same thing is bad practice. see this question. This guideline article pretty clearly states why

Catching exceptions that you cannot legitimately handle hides critical debugging information.

Conrad Frix