Diadistis
Diadistis

Reputation: 12174

Static exception instance

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;
        ....
    }
}

Upvotes: 1

Views: 840

Answers (1)

Rob Walker
Rob Walker

Reputation: 47462

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.

Upvotes: 9

Related Questions