Firstly, it sounds like you may be using try/catch too often - particularly if you're catching Exception
. try/catch blocks should be relatively rare; unless you can really "handle" the exception, you should just let it bubble up to the next layer of the stack.
Now, assuming you really do want all of these try/catch blocks, why is it not an option to create a delegate? With anonymous methods and lambda expressions, as well as the Func/Action delegates in the System
namespace, there's basically very little work to do. You write:
public void SurroundWithTryCatch(Action action)
{
try
{
action();
}
catch(Exception ex)
{
//something even more boring stuff
}
}
and then your SurroundWithTryCatch(MyMethod)
will work fine, if it takes no paramaters.
Alternatively, if you don't want to call a different method, just write:
public void MyMethod()
{
SurroundWithTryCatch(() =>
{
// Logic here
});
}
If you need to return from the method, you can do:
public int MyMethod()
{
SurroundWithTryCatch(() =>
{
// Logic here
return 5;
});
}
with a generic overload of SurroundWithTryCatch
like this:
public T SurroundWithTryCatch<T>(Func<T> func)
{
try
{
return func();
}
catch(Exception ex)
{
//something even more boring stuff
}
}
Most of this would be fine in C# 2 as well, but type inference won't help you quite as much and you'll have to use anonymous methods instead of lambda expressions.
To go back to the start though: try to use try/catch less often. (try/finally should be much more frequent, although usually written as a using statement.)