Search code examples
asp.netresponse.write

Do I need Response.End() in ASP.Net 2.0


I am just starting with ASP.Net. I copied a ex-co-worker's code (from .Net 1.1 era) and it has a Response.End(); in case of an error. There is also a:

        catch (Exception ex)
        {
            Response.Write(ex.Message);
            Response.End();
        }

at the end of Page_Load(object sender, System.EventArgs e) which always appends "Thread was aborted." or something like that at the end. I suspect that this worked differently before, or the error conditions were not tested very well.

Anyhow, I was able to stop using Response.End(); in case when I do not like the GET parameters, and use return; instead. It seemed to do the right think in a simple case.

Is this Ok in general?

There are some problems with the code I copied, but I do not want to do a rewrite; I just want to get it running first and find wrinkles later. The Response.End(); caused a mental block for me, however, so I want to figure it out.

I want to keep the catch all clause just in case, at least for now. I could also end the method with:

        catch (System.Threading.ThreadAbortException)
        {
            Response.End();
        }
        catch (Exception ex)
        {
            Response.Write(ex.Message);
            Response.End();
        }

but that just seems extremely stupid, once you think about all of the exceptions being generated.

Please give me a few words of wisdom. Feel free to ask if something is not clear. Thanks!

P.S. Ex-coworker was not fired and is a good coder - one more reason to reuse his example.


Solution

  •  catch (System.Threading.ThreadAbortException)
        {
            Response.End();
        }
        catch (Exception ex)
        {
            Response.Write(ex.Message);
            Response.End();
        }
    

    This actually won't even work. ThreadAbortException is a special case exception, and when your catch block is done, it is automatically re-thrown.

    Just using return is definitely the best case, if the method you are in is the last thing that will be run in terms of your code. If it's not, and you want to end the request gracefully, you can call HttpApplication.CompleteRequest(), which will skip processing the rest of the lifecycle and jump directly to the EndRequest event processing.