Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 223
Alejandro Huerta Avatar asked Nov 06 '13 18:11

Alejandro Huerta


2 Answers

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; })
like image 76
pobrelkey Avatar answered Oct 09 '22 20:10

pobrelkey


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

ExecuteInTryCatch( ()=>{
    // stuff here
});
like image 38
Marc Gravell Avatar answered Oct 09 '22 19:10

Marc Gravell