views:

118

answers:

1

Hello,

Are static exception instances safe to use? Any good reason to avoid the following?

public class ResourceHttpHandler : IHttpHandler
{
    private static HttpException notFoundException =
                new HttpException(
                    (int)HttpStatusCode.NotFound,
                    "Assembly Not Found");

    public bool IsReusable
    {
        get { return true; }
    }

    public void ProcessRequest(HttpContext context)
    {
        ....
        throw notFoundException;
        ....
    }
}
+8  A: 

An exception's stacktrace is set when it is thrown (http://msdn.microsoft.com/en-us/library/system.exception.stacktrace.aspx), so this code is not thread safe.

Multiple threads will be using the same exception object and anyone relying on the content of the exception will get confusing results.

Rob Walker
Thanks, I was sure there was something wrong, I just couldn't find out what :)
Diadistis