Hey everyone, I was thinking about passing method blocks around as arguments to helper classes that built in exception handling but it's one of those things that is intuitive and I'd like to submit it for criticism, insight, or advice.
I would like to note up front that this is NOT how I do all of my exception handling, but there are cases where I find this structure more "readable."
For example, I have a scenario where I'm showing a preview image but if that fails (this is a real scenario where I'm previewing images and certain GIF/BMP formats cannot be previewed) it's simply a scenario where I display an alternate image instead of preview. The try/catch code block that looks like this:
try
{
alternatePreviewImage.SetSource(fs);
}
catch (Exception ex) {
requiresSpecialPreview = false;
previewImage = new BitmapImage(new Uri("Images/NoPreviewAvailable.png", UriKind.Relative));
}
So I'll leverage a helper class that takes a method parameter to make it look like this:
if(!ErrorHelper.RunWithSuccessNotify(()=> alternatePreviewImage.SetSource(fs))){
requiresSpecialPreview = false;
previewImage = new BitmapImage(new Uri("Images/NoPreviewAvailable.png", UriKind.Relative));
}
The ErrorHelper.RunWithSuccessNotify is quite simple:
public static bool RunWithSuccessNotify(Action code) {
bool success = true;
try
{
code();
}
catch (Exception ex)
{
success = false;
}
return success;
}
Let me again underscore that it is useful for these low impact scenarios, as well as others where I may be able to suppress the exception:
public static void RunWithErrorSuppression(Action code) {
try
{
code();
}
catch (Exception ex)
{
// pass
}
}
The approach could be more detailed too, to allow for capturing the exception:
public static void ExecuteWithLogging(Action code, Action<Exception> handles) {
try
{
code();
}
catch (Exception ex)
{
handles(ex);
}
}
So what are thoughts on this set of tactics to centralize exception handling? If it is a bad direction, are there specific reasons why it might end up getting me in trouble?