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

后端 未结 11 1141
星月不相逢
星月不相逢 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:53

    I tend to disagree with the premise of your question:

    In a nutshell, I need a standard exception that should be thrown when an application configuration setting is missing or contains an invalid value. You'd think the Framework had such an exception baked into it for applications to use. (It apparently did, but it was marked obsolete, and was replaced by something much larger in scope.)

    According to the MSDN documentation on System.Exception (Exception Class, you really shouldn't be throwing exceptions for user input errors, for performance reasons (which has been pointed out by others on Stack Overflow and elsewhere). This seems to make sense as well - why can't your function return false if the user input is entered incorrectly, and then have the application gracefully exit? This seems to be more of a design problem then an issue with which Exception to throw.

    As others have pointed out, if you really have to thrown an exception - for whatever reason - there isn't any reason why you couldn't define your Exception type by inheriting from System.Exception.

提交回复
热议问题