Steve said:
I have a couple of standard Try/Catch blocks that I use repeatedly. Is there
anyway to wrap these blocks into a method call? Or does C# have anything like a
C++ macro?
As suggested by others, you can use delegates combined with functions,
but that has the disadvangate of Exception wrapping:
delegate-invocations doesn't directly throw exceptions, but throws an
exception with the original exception as it's .Inner. This is
understandable with async execution of delegates but I cannot find any
reason for the behaciour with sync. invoked delegates.
Also the delegate-approach requires a delegate for every signarure of
the code to exec, making for almost as big a mess as copying try...catch.
You could consider whether your prorgam could be implemented with less
catch-clauses. I usually advice to catch only when one of:
- You can fix the situation: try another way, ...
- You are at the top of the stack
A special exception from this is catch for logging:
try {
...
} catch ( Exception e ) {
Logging.Log(e);
throw;
}
If you find that the catch-logic is actually "finally" logic, and there
is a 1-1 relation between the code to exec and the error, you can use
the "using" pattern for cleanup.
Finally, if all else fail, you can try to factorize the body of the
catch-handler into a function so you wont have to copy all the
exception-handling code into every catch-block.