Definitive Guide to Exception Handling

Greetings,

In my experience, I've realized that no matter what the programming language is, there is no consense regarding what is the best practice when handling exceptions.

Well, i thought about posting this one because it is really hard to find some article that discusses that out there and i hope you all can take advantage of the opinions that i hope people will begin to post here.

The problem i propose is the following: let's suppose you have a method which calls a few System.* methods. Each of these methods throw at least 1 exception and you wanna make sure you are prepared to catch each and every error.

One sample of this cenario would be when you want to send content over HTTP programmatically. What you have to do is create an HttpWebRequest object (with a proper URL), have some string content, transform this very content into byte array and then get the stream and write to that stream. Let's focus on the writing process.

Stream1 = HttpWebRequest1.GetRequestStream();
Stream1.Write(ByteArrayContent, 0, ByteArrayContent.Lenght);
Stream1.Dispose();

Normally, we would wrap this snippet on a try...catch block (let's forget about "using" statement for now). So:

try
{
Stream1 = HttpWebRequest1.GetRequestStream();
Stream1.Write(ByteArrayContent, 0, ByteArrayContent.Lenght);
}
finally
{
Stream1.Dispose();
}

The big question is: how to handle the exceptions thrown by the HttpWebRequest.GetRequestStream() method (which are five for .net 2.0) and Stream.Write() (which are six for .net 2.0). Bear in mind that some of the exceptions occur in both methods, so how can one differentiate. Would it be one try...catch block, multiple isolated try...catch blocks or nested try...catch blocks

I would probably create a custom Exception (which inherits System.Exception) to provide to the above layer a custom interface where it would look for (and possibly log) errors. How do you feel about it

Well... i hope experienced programmers can contribute to this problem and i feel that will shed a light on the exception handling doubts. I thanks in advance for everyone who can help.

Yours,

Chuck



Answer this question

Definitive Guide to Exception Handling

  • tattoo

    Peter,

    I really appreciate your input. Indeed, the links you provided contain a lot of new information to me. I, however, failed to find the particular information i was looking for. I've read the guidelines you provided and other guidelines from the web and all i can find is general rules to exception handling. And, surprinsinly this is such an obscure subject that even in the forum links you've listed, one can not find a consensus. Last but not least, some source code i cared to read (it was actually the Atlas Framework) did not follow many of the "DOs" from the guidelines.

    Back to my example, as i said, we have a bunch of exceptions that both methods throw. What i initially propose, would be something like this (consider this class is named HttpModule):

    try
    {
    Stream1 =
    this.HttpWebRequest1.GetRequestStream();
    Stream1.Write(ContentByteArray, 0, ContentByteArray.Length);
    }
    #region HttpWebRequest.GetRequestStream() exceptions
    catch (InvalidOperationException)
    {
    }
    catch (ObjectDisposedException)
    {
    }
    catch (WebException)
    {
    }
    catch (NotSupportedException)
    {
    }
    catch (ProtocolViolationException)
    {
    }
    #endregion
    #region
    Stream.Write() exceptions
    catch (IOException)
    {
    }
    // Already catched
    //catch (NotSupportedException)
    //{
    //}
    // Already catched
    //catch (ObjectDisposedException)
    //{
    //}
    catch (ArgumentNullException)
    {
    }
    catch (ArgumentException)
    {
    }
    catch (ArgumentOutOfRangeException)
    {
    }
    #endregion
    finally
    {
    Stream1.Dispose();
    }

    Well... suffice to say that this code is "unusual" at best... not mention weird, big, clumsy etc... But the fact is that it DOES catch all exceptions and it is NOT using catch (Exception) {} snippet. In each and every one of those catch blocks, i would throw a new HttpModuleException (my class) which would carry the propper InnerException and some custom message and parameters. That way, it would be easier to show frienlier error messages to the user at the presentation layer.

    Problems ! Sure! As i've mentioned on the previous post: how to find out if NotSupportedException was thrown by .GetRequestStream() or by .Write() And of course, what would you all think of this approach to exception handling

    Again, I appreciate any inputs and thank Peter for the help he's provided so far.


  • Endo64

    BTW, as with most things in software development, there really isn't a "definitive guide". There's generally accepted guidlines and point you in the right direction; but for the most part is depends on your situation. A guide can't take into consideration the performance, security, etc. requirements that your software has that govern what you will and won't do with exceptions.

  • Steve98796

    If you haven't purchased it already, the Framework Design Guidelines has some excellent information on the subject.

    I suggest reading the following:

    As well, the following may be interesting

    There also various discussions on this site regarding exception throwing and handling, especially in the FxCop forum.



  • Kinju

    Carlos Mendonca wrote:

    Peter,

    I really appreciate your input. Indeed, the links you provided contain a lot of new information to me. I, however, failed to find the particular information i was looking for. I've read the guidelines you provided and other guidelines from the web and all i can find is general rules to exception handling. And, surprinsinly this is such an obscure subject that even in the forum links you've listed, one can not find a consensus. Last but not least, some source code i cared to read (it was actually the Atlas Framework) did not follow many of the "DOs" from the guidelines.

    Back to my example, as i said, we have a bunch of exceptions that both methods throw. What i initially propose, would be something like this (consider this class is named HttpModule):

    try
    {
    Stream1 =
    this.HttpWebRequest1.GetRequestStream();
    Stream1.Write(ContentByteArray, 0, ContentByteArray.Length);
    }
    #region HttpWebRequest.GetRequestStream() exceptions
    catch (InvalidOperationException)
    {
    }
    catch (ObjectDisposedException)
    {
    }
    catch (WebException)
    {
    }
    catch (NotSupportedException)
    {
    }
    catch (ProtocolViolationException)
    {
    }
    #endregion
    #region
    Stream.Write() exceptions
    catch (IOException)
    {
    }
    // Already catched
    //catch (NotSupportedException)
    //{
    //}
    // Already catched
    //catch (ObjectDisposedException)
    //{
    //}
    catch (ArgumentNullException)
    {
    }
    catch (ArgumentException)
    {
    }
    catch (ArgumentOutOfRangeException)
    {
    }
    #endregion
    finally
    {
    Stream1.Dispose();
    }

    Well... suffice to say that this code is "unusual" at best... not mention weird, big, clumsy etc... But the fact is that it DOES catch all exceptions and it is NOT using catch (Exception) {} snippet. In each and every one of those catch blocks, i would throw a new HttpModuleException (my class) which would carry the propper InnerException and some custom message and parameters. That way, it would be easier to show frienlier error messages to the user at the presentation layer.

    Problems ! Sure! As i've mentioned on the previous post: how to find out if NotSupportedException was thrown by .GetRequestStream() or by .Write() And of course, what would you all think of this approach to exception handling

    Again, I appreciate any inputs and thank Peter for the help he's provided so far.

    Many people view exception handling like a religion--they have blind faith in what they believe. Any of the guidelines you see only make your program more robust; people will argue things like "catching Exception isn't bad"; but they just haven't encountered a situation where it doesn't work, i.e. they've only used it to catch exceptions they *can* handle.

    Your assumption that it's catching *all* exceptions is wrong. You're catching all *documented* exceptions. .NET does not have any way to guarantee that a member only throws certain exceptions. OutOfMemoryException, StackOverFlowException, etc. are other exceptions where it's taken for granted that they might get thrown. A guideline is, only catch and not rethrow exceptions that you can actually compensate for. OutOfMemoryException is an example of an exception you realistically can't compensate for. In your example. protocol-related exceptions are good to handle, you can hope the Message member has something the user can understand; but generally your program can continue running after it receives one of those exceptions. Other logic error type exceptions like ObjectDisposedException, ArugumentNullException, or ArgumentOutOfRangeException are great to know about when you're developing the software; but what can you possible do with these exceptions to let the program continue running reliably



  • Definitive Guide to Exception Handling