Search code examples
c#exceptionconstructorstatic-classes

Exception in static constructor


I've dug around SO for an answer to this, and the best one I can find so far is here, however that is geared toward instances with static constructors; I'm only using the class statically.

My code:

public static class MailHelper {

    private static string mailHost;

    static MailHelper() {

        var mailSettings = ConfigurationManager.GetSection("MailSettings") as NameValueCollection;
        if (null == mailSettings) {
            throw new ConfigurationErrorsException("Missing Mail Settings in the configuration file");
        }

        mailHost = ConfigurationManager.AppSettings["mailHost"];
        if (null == mailHost) {
            throw new ConfigurationErrorsException("Missing mailHost setting in the configuration file");
        }

    }

    public static void SendMail(MailMessage Message) {
        ...
    }

}


try {
    MailHelper.SendMail(Message);
}
catch (ConfigurationErrorsException exc) {
    ...
}

//  ???    
MailHelper.SendMail(Message);


.

So if the static constructor throws an exception the first time it's called, what happens the second time I try to access the static SendMail() method?

PS: Sorry if you don't like Stroustrup's version of K&R brace styling, but don't edit my post just to change the braces to your preferred Allman style. Thanks.


Solution

  • The other two answers are good answers to your direct question - here's a metaanswer - you should be throwing the exception in the method when you detect that the configuration elements are not populated, rather than in the constructor. IMHO, "not configured" is a valid configuration state for those elements at the constructor phase, just not at SendMail time. That will sidestep this whole problem.