Documenting my journey through the pratice of software development RSS 2.0
 Thursday, May 01, 2008

I hate the Try Catch syntax in C# - it's bulky, ugly, and makes my code hard to read.

try
{
  // do some stuff here
}
catch
{
  //handle exceptions here
}
finally
{
  //clean up here
}

Although very functional and well documented, to the point where it can be effectively used, I don't see the elegance that I want in my language - especially if you actually have to catch a specific exception and deal with it in the middle of your functional code.

So, I'll create the elegance that I want.

public class TryCatch
{
 
    public static Exception Do(Action action)
    {
        Exception caughtException = null;
        try
        {
            action();
        }
        catch(Exception ex)
        {
            caughtException = ex;
        }
        return caughtException;
    }
 
}

With this very basic implementation, using lambda expressions, I can create a much more friendly syntax to use:

Exception ex = TryCatch.Do(() => 
{
  //Do Stuff Here, with assurance that an exception will be caught, if thrown.
});
 
//send the exception off to the exception processing / handling, if needed.

From there, you could add a "fluent" interface to catch specific exceptions, have a finally block, etc - but you end up with the same ugliness that I wanted to avoid.

//Blech. This just puts us right back in ugly-ville
TryCatch.Do(() =>
{
    //throw exception here
}).Catch<Exception>(() =>
{
    //handle exception here
});

ugh - ugly, for that matter. That didn't help us at all. And we don't need it, anyway. You are guaranteed to have the before and after TryCatch.Do execute.

//setup
IDBConnection conn = GetMyConnection();
 
TryCatch.Do(() =>
{
    //execute
    conn.Open();
});
 
//cleanup
if (conn != null)
  conn.Dispose();

I like it.

Thursday, May 01, 2008 6:42:13 PM (Central Standard Time, UTC-06:00)  #    Comments [0]. Trackback 
Tags: .NET | General | Lambda Expressions

Comments are closed.
Navigation
About Me
View Derick Bailey's profile on LinkedIn

Send mail to the author(s) Contact Me
Archive
<August 2008>
SunMonTueWedThuFriSat
272829303112
3456789
10111213141516
17181920212223
24252627282930
31123456
About the author/Disclaimer

Disclaimer
The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.

© Copyright 2008
Derick Bailey
Sign In
Statistics
Total Posts: 65
This Year: 65
This Month: 4
This Week: 0
Comments: 25
Themes
Pick a theme:
All Content © 2008, Derick Bailey
DasBlog theme 'Business' created by Christoph De Baene (delarou)