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.