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 love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With