Saturday, December 24, 2011

Try.Catch.Crap! Getting a string safely without repeating yourself

One thing that comes up a lot is when/where to write try/catch blocks.

When trying to follow DRY, it's often frustrating when you need exactly the same value but in scenario 1 you want the getter to throw if the value is not available, but in scenario 2 you want a default value if the value is not available. I had just such a situation yesterday.

So, I wrote this handy exception safe string getter:

private string TryGetStringOrDefault( Func pFunc, string pDefaultValue )
{
    try
    {
        return (pFunc());
    }
    catch( Exception ex )
    {
        Log.Error( ex );
    }
    return pDefaultValue;
}

As you can see, I have a logger in place but you could also pass in an exception handler.

To use this function, do the following:

TryGetStringOrDefault( GetSemaphoreUrlOrThrow, string.Empty );

The second parameter is what gets returned if an exception gets thrown.

Even better is the generic version. I've started using these wrappers a lot. It's starting to feel like something that should be in the language. I hope this happens. We used to check everything for null and now we have things like the ?? operator.

Who knows, maybe one day soon instead of doing try/catch you'll be able to write:

try( func() ).onfail( DoThis() ).finally( FinishWithThis() );

No comments:

Post a Comment