The TryThis method


The more I learn and use dynamic languages like JavaScript and Ruby, the more I feel the constraints placed on me by the C# compiler.  Today I needed to wrap a bunch of calls to a web service facade in some try catch statements.  I really hated the idea of littering my code with these because a lot them make the code that much harder to read.  What I really wanted was a method that would execute the statement in a try/catch and do the necessary exception handling for me. In this situation, the method calls were very different (number of parameters, return values), but the error handling was exactly the same.

What I really wanted was something like the block statement in Ruby, where I just pass in arbitrary code to a method that would then execute it.  It was a little trickier in C# because of the variations in the method signture.  A method that had a Func parameter wouldn’t work because I had varying number of parameters.  Also the changing return value added a nice twist.  In the end, it came out rather nice.

With this little method I can now pass in any method and

private bool TryThis(Action block)
        {
            
try
            {
                block();
                
return true;
            }
            
catch(Exception)
            {
                
//do something with exception here
                return false;
            }
        

Here are a few tests to show what it looks like.</p>

public interface Foo
    {
        
DateTime Bar(string a, string b);
        
string Bar2(int a);
        
void Bar3(int a, int b);
    }
    [
TestFixture]
    
public class trythis_specs
    {
        
private Foo mock;</p>

        [</span>SetUp]
        
public void setup()
        {
            mock =
MockRepository.GenerateMock<Foo>();
        }
       [
Test]
      
public void should_return_true_when_there_is_no_exception()
       {
           mock.Stub(m => m.Bar(
“a”, “b”)).Return(DateTime.Now);
          
DateTime output;
          
bool result = TryThis(() => output = mock.Bar(“a”, “b”));
          
Assert.That(result);</p>

       }
       [</span>Test]
        
public void can_get_the_value_from_executing_method()
       {
          
var time = DateTime.Now;
           mock.Stub(m => m.Bar(
“a”, “b”)).Return(time);
          
DateTime output = DateTime.MinValue;
          
bool result = TryThis(() => output = mock.Bar(“a”, “b”));
          
Assert.That(output, Is.EqualTo(time));
       }
       [
Test]
        
public void return_false_on_exception()
        {
           mock.Stub(m => m.Bar3(1,2)).Throw(
new Exception());
          
var result = TryThis(() => mock.Bar3(1,2));
          
Assert.That(result, Is.False);
        

</div> </div> </div>

That’s not quite as clean a block parameter in Ruby, but I can live with it for now.

Wiring Up Generics In Castle Windsor