.NET: Which Exception to Throw When a Required Configuration Setting is Missing?

后端 未结 11 1108
星月不相逢
星月不相逢 2020-12-23 20:18

Here\'s a standard scenario:

if(string.IsNullOrEmpty(Configuration.AppSettings[\"foobar\"]))
   throw new SomeStandardException(\"Application not configured          


        
11条回答
  •  时光取名叫无心
    2020-12-23 20:50

    As Daniel Richardson said, ConfigurationErrorsException is the one to use. In general it is only recommended to create your own custom Exception types if you have a scenario to handle them. In the case of configuration errors, which are usually fatal, this is rarely the case so it's usually more appropriate to reuse the existing ConfigurationErrorsException type.

    Prior to .NET 2.0, the recommendation was to use System.Configuration.ConfigurationException. ConfigurationException became obsolete in .NET 2.0, for reasons which were never clear to me, and the recommendation changed to use ConfigurationErrorsException.

    I use a helper method to throw the exception so that it's easy to change the exception being thrown in one place when migrating from .NET 1.x to 2.0, or if Microsoft decides to change the recommendation again:

    if(string.IsNullOrEmpty(Configuration.AppSettings("foobar")))
    {
       throw CreateMissingSettingException("foobar");
    }
    
    ...
    
    private static Exception CreateMissingSettingException(string name)
    {
        return new ConfigurationErrorsException(
            String.Format
            (
            CultureInfo.CurrentCulture,
            Properties.Resources.MissingConfigSetting,
            name
            )
            );
    }
    

提交回复
热议问题