سؤال

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.

هل كانت مفيدة؟

المحلول

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; })

نصائح أخرى

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

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

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.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top