If you were catching a SettingsFileNotFoundException at a different level (in a different, calling method), then it would be wise to create a custom exception, because you might need to determine what exactly happened. The following is a simplified example:
void startingMethod() { try { secondMethod(); thirdMethod(); } catch (SettingsFileNotFoundException sfnfe) { // Handle all SettingsFileNotFoundException issues here. } catch (Exception ex) { // Handle all other exceptions here. } } void secondMethod() { // TODO: secondMethod actions. var fileName = SomeLogicSpecificToSecondMethodHere(); if (!File.Exists(fileName)) { throw new SettingsFileNotFoundException("..."); } } void thirdMethod() { // TODO: thirdMethod actions. var fileName = SomeOtherLogicSpecificToThirdMethodHere(); if (!File.Exists(fileName)) { throw new SettingsFileNotFoundException("..."); } }
In the above example, the program looks for several settings files and, therefore, has several throw () statements that use an exception. And the nested exception exception allows you to handle all of these exceptions the same way, without putting the same code in your secondary methods. Here, if your custom exception as a different type allows you to handle a specific exception, different from the rest of your error handling.
But assuming that you are not dealing with this error handling error, the first approach you described is better because it is generalized. Why do you throw an exception that can only be thrown once? I assume that you cache your settings in variables, so you donβt need to read your file every five seconds, thereby giving you the opportunity to use a new exception limited to one time during application initialization.
So, in your case, if you are most likely not going to extend your code to use more complex error handling in the future, you should probably just use a very specific FileNotFoundException exception message.
source share