Exception safety/handling with .Net HtmlTextWriter?

615 Views Asked by At

I am using a .Net HtmlTextWriter to generate HTML.

try
{
   htw.RenderBeginTag( HtmlTextWriterTag.Span );

   htw.Write(myObject.GenerateHtml());

   htw.RenderEndTag( );
}
catch (Exception e)
{
   GenerateHtmlErrorMessage(htw);
}

In this example, if an error exception is fired during myObject.GenerateHtml(), I will generate a nice error html but it will be preceded by an opening span tag that is never closed.

I could refactor it like so

try
{
   string myHtml = myObject.GenerateHtml();

   // now hope we don't get any more exceptions
   htw.RenderBeginTag( HtmlTextWriterTag.Span );
   htw.Write(myHtml)     
   htw.RenderEndTag( );
}
catch (Exception e)
{
   GenerateHtmlErrorMessage(htw);
}

Now my span doesn't open 'till I've done the hard work, but this just looks awkward to me. Is there any way do rollback with a HtmlWriter? Even if I had to put in loads of using blocks.

I'm currently working in .Net 2.0, but a discussion of solutions in 3.5 would be ok.

2

There are 2 best solutions below

0
On BEST ANSWER

If you are only concerned about errors that occur during the GenerateHtml() call, and don't like the second approach (which seems fine to me), why not move the closing span tag into a finally block, and pull out the open call:

htw.RenderBeginTag( HtmlTextWriterTag.Span );
try
{
   htw.Write(myObject.GenerateHtml());
}
catch (Exception e)
{
   GenerateHtmlErrorMessage(htw);
}
finally
{
   htw.RenderEndTag( );
}

This way the span is always opened and always closed. If GenerateHtml throws an exception, you catch it and generate the error inside the span, before closing it.

Of course, if the exception occurs trying to write the tags, then you are out of luck writing an error message anyway, so I'll assume that is being handled elsewhere.

6
On

You should avoid using try/catch, and instead check if the result is not what you expected. The only thing I can see here, is that myHTML can be null, so try something like this:

string myHtml = myObject.GenerateHtml();

if (myHTML != null)
{
   htw.RenderBeginTag( HtmlTextWriterTag.Span );
   htw.Write(myHtml)     
   htw.RenderEndTag( );
else
{
   GenerateHtmlErrorMessage(htw);
}