Is using Lambda expression for try without catch a bad practice?
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
{
开发者_JS百科 // ignore.
}
}
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.
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.
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.
the void Try (Action a)
is rather obscure the other approach is easier to read
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.
精彩评论