I have a simple problem in my project (C# based Windows Service) which I just cannot wrap my head around.
In several classes of my application I need to load an interval (time span), from the application configuration. In the configuration file this timespan is stored as a string, such as "1d8h". Obviously, the application needs to parse this string before it can use the time span. In one case, I am passing this string as an argument to a constructor while initializing several objects which all have their own time span. In the constructor I am then parsing this string and throwing an ArgumentException
if the parsing fails for whatever reason.
Somewhere else in my application I need to do the exact same thing, but this time in a static constructor which is not allowed to have any arguments. In this case, I am throwing a System.Configuration.ConfigurationErrorsException
because I am not working with any arguments so throwing an ArgumentException
would not be correct in this case.
Is it perfectly fine to throw different exceptions in both cases, despite them being caused by the exact same operation? If not, what should I do instead?
CodePudding user response:
I suggest to use FormatException in both cases.
As you said, ArgumentException
signals a problem with an argument, usually its type or kind (while ArgumentNullException
is used specifically for null arguments). Therefore, neither is acceptable in a static constructor accepting no arguments.
FormatException
fits nicely. It signals a problem with the format of the argument itself, rather than its type or kind. It is thrown by most of C#'s native .Parse()
methods, such as DateTime.Parse()