In a similar situation, I did the following. I will show the technique in two stages ...
Step 1. Create a method that provides a specific execution context for another code:
// this static method is responsible for setting up a context for other code // to run in; specifically, it provides the exception handling "plumbing": public static void guarded(Action action) { // ^^^^^^^^^^^^^ try // actual code to be executed { action(); } catch (SomeExceptionA ea) { // handle exception... } catch (SomeExceptionB eb) { // handle exception... } // etc. }
Step 2. Apply this context to any piece of code:
Then you simply “end” the exception handling around the actual code in your methods:
public void MethodA() { guarded(() => // <-- wrap the execution handlers around the following code: { // do something which might throw an exception... }); } public void MethodB() { guarded(() => { // do something which might throw an exception... }); }
Summary:
The general idea here is to write a function ( guarded in the example above) that sets a specific execution context for other code to run. (The context in this example provides exception handling.) The code to be executed in this context is provided as a lambda function. You can even adapt the context creation function so that the code in the lambda function can return a value.
stakx
source share