Using a generic class to execute with try / catch / finally?

I found that in my code there is a lot of this in different methods:

try
{
  runABunchOfMethods();
}
catch (Exception ex)
{
  logger.Log(ex);
}

How about creating this:

public static class Executor
{

    private static ILogger logger;

    public delegate void ExecuteThis();

    static Executor()
    {
        // logger = ...GetLoggerFromIoC();
    }

    public static void Execute<T>(ExecuteThis executeThis)
        where T : Exception
    {
        try
        {
            executeThis();
        }
        catch (T ex)
        {
            // Some kind of Exception Handling Strategy...
            logger.Log(ex);
            // throw;
        }
    }

}

And just using it like this:

private void RunSomething()
{
  Method1(someClassVar);
  Method2(someOtherClassVar);
}

...

Executor.Execute<ApplicationException>(RunSomething);

Are there any flaws in this approach? (You can add Executor methods and delegates when you want to finally use and use generics for the type of Exeception you want to catch ...)

: - , , , , , , , , , / . try.../runABunchOfMethods-part ( ), runABunchOfMethods, , , " ".

, / , .

Executor, T, exeception , , . catch: es , , , .

+5
9

, , AOP, PostSharp. , , () .

EDIT:

try/catch postsharp - , PostSharp:

[Serializable]
public class CommonExceptionHandling : OnExceptionAspect
{
    public override void OnException(MethodExecutionEventArgs eventArgs)
    {
        // can do some logging here
        // ...

        // throw the exception (out of postsharp) to where it occurred:
        eventArgs.FlowBehavior = FlowBehavior.RethrowException;                       

        // If you want to ignore the exception, you can do this:
        //eventArgs.FlowBehavior = FlowBehavior.Return;

        base.OnException(eventArgs);
    }
}

, , , .

+2

- . Exception . ; , , , , , .
, , .

:
, ?
, , System.Exception? ?

( OP):
, . Basicall ( - ). Executor.Hide<ApplicationException>( RunSomething );, , . - ? . , , , . , , , .
(throw ex throw, ). ? . , , ... ? ?
, . . , .

:
try catch?

+12

, ( , ).

+3

, :

  • ( , , )
  • Executor.Execute, Method1 (...). , .
  • ...
+2

. , - . SMTP- ? , , .

, ( , ), , .

+1

, - :-) , ( "", "" (ex) "), , (, , , ), .

, , , AppDomain.UnhandledException, , ( ) ? , catch, , .

+1

" , ". - " " . , , , DB.

, , "" .

+1

catch .

  • Main.
  • WinForms .
  • , ThreadProcs .
  • Etc.

, , . , .

, , , , "" .

+1

....

, , .

try 
{ 
  runABunchOfMethods(); 
} 
catch (Exception ex) 
{ 
  logger.Log(ex); 
} 

. ( ).

, , , , .

0

All Articles