Alejandro Huerta
Alejandro Huerta

Reputation: 1144

Pass block of code as parameter and execute in try catch

TL;DR: I'd like to pass some code that will then be executed within a try catch Pseudo code:

void ExecuteInTryCatch(BlockOfCode)
{
   try
   {
      execute BlockOfCode with possible return value
   }
   catch (MyException e)
   {
      do something
   }
}

Long Version: I'm writing automation tests of a web application and would like to execute some code that will catch certain exceptions that may result from non-deterministic reasons and retry executing that code for a certain time out before finally throwing the exception. I've looked at possibly using a delegate for this purpose but am pretty confused how I would accomplish this and I've never used lambda expressions and that's even more confusing.

The goal is to be able to reuse this code for various selenium actions. This is fairly simply with Ruby but not so much in C#, personally.

Upvotes: 5

Views: 3682

Answers (3)

pobrelkey
pobrelkey

Reputation: 5973

Further to the other answer: if you need a return value, use Func instead of Action.

// method definition...
T ExecuteInTryCatch<T>(Func<T> block)
{
    try
    {
        return block();
    }
    catch (SomeException e)
    {
        // handle e
    }
}

// using the method...
int three = ExecuteInTryCatch(() => { return 3; })

Upvotes: 10

David Pilkington
David Pilkington

Reputation: 13628

If you want to have the code return a value, use a Func

T ExecuteInTryCatch<T>(Func<T> codeBlock)
{
    try
    {
        codeBlock();
    }
    catch (SomeException e)
    {
        //Do Something
    }
 }

otherwise use am Action

void ExecuteInTryCatch(Action codeBlock)
{
   try
   {
       codeBlock();
   }
   catch (MyException e)
   {
       //Do Something
   }
}

You can go even future and define your own delegates to restrict the expressions that are passed in.

Upvotes: 0

Marc Gravell
Marc Gravell

Reputation: 1063774

void ExecuteInTryCatch(Action code)
{
   try
   {
       code();
   }
   catch (MyException e)
   {
      do something
   }
}

ExecuteInTryCatch( ()=>{
    // stuff here
});

Upvotes: 6

Related Questions