Custom exception versus inline exception with a very descriptive message

Today I came across an interesting situation: I have a small application with a settings file that is well documented in the documentation, but if there is no file, then what would be better: throw a filenotfoundexception and give a very depressing message that the settings file is not available or create a custom an exception (already a drawback is working in this case, although it will take 10 minutes) called SettingsFileNotFoundException. This will immediately drop it, what is the problem.

The problem with the first approach (standard exception + message) is that in a command environment it will only work if it is a strictly followed procedure.

Although I am not very interested in the specifics of the language here, the language is C #.

What would be better?

thanks

+4
source share
1 answer

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.

+3
source

Source: https://habr.com/ru/post/1346632/


All Articles