Let’s get this out of the way – I think exceptions are better error handling technique than error codes. There – I’ve said it. Even though I respect Joel and his writing is most excellent, I disagree with all of his posts that denounce exceptions in favor of error codes.
That said, exceptions are not the silver bullet for the error handling, but then again nothing ever is. This posts’ goal is to help with a small annoyance that you can run into when using a library that throws the same 2–3 exceptions most of the time, you call it on many places and handle exceptions in the same way all the time.
Take Socket class for example – most of its methods will throw SocketException or ObjectDisposedException. If you have dozens of calls to any of these methods, your code will look like this
try
{
byte[] buff = new byte[1024];
s.Receive(buff);
}
catch(SocketException se)
{
// do some cleanup
}
catch(ObjectDisposedException ode)
{
// do (the same or) some other cleanup
}
Repeat, ad nauseam. Isn’t there a better way to handle this? There is, but note one important thing: the cleanup code is always the same (as comments state) for each exception handled, otherwise what follows does not help.
If you take a good look at all these calls, you will notice that the common part is what is inside the try block, while the rest is identical. So the problem boils down to capturing the lines of code in the try block. This is easy to achieve using an anonymous method. Code first, discussion later.
internal delegate void VoidMethodNoParams();
internal static void CommonSocketMethod(VoidMethodNoParams vmnp)
{
try
{
vmnp.Invoke();
}
catch (SocketException se)
{
// handle socket exception
}
catch (ObjectDisposedException ode)
{
// handle object disposed exception
}
}
// the above code can be used like this (assuming the method is in class Helper)
Helper.CommonSocketMethod(
delegate {
byte[] buff = new byte[1024];
s.Receive(buff);
});
That's it! Take few lines of code, enclose them in curly brackets, put keyword delegate in front and you’ve got a suitable method. Another .NET 2.0 feature is at play here too – you don’t have to create a delegate and then assign a method (including anonymous methods) to it – all of it can be inferred from your code. Even better, if your app is a WinForms app, there is already a delegate with no return value that accepts no parameters called MethodInvoker so you don’t have to declare your own (like I did with VoidMethodNoParams).
Disclaimer: this is not a technique to help you to generically ignore exceptions. It is only useful as a way to clean up the code when the exception handling code repeats many times. In all other cases, you should have “normal” try/catch/finally blocks.
Be the first to rate this post
- Currently 0/5 Stars.
- 1
- 2
- 3
- 4
- 5