Custom exception vs built in exception with very descriptive message
I came across an interesting situation today: I have a small app with a settings file, which is well documented in the documentation, but if the file is not there, what would be better: throw a filenotfoundexception and give a very depressive message that the settings file is not available, or create a custom exception (already, the disadvantage is the work in doing this, even though it'll take 10 minutes) called SettingsFileNotFoundException. This will give it away immediately, what the problem is.
The issue with the first approach (standard exception + message), is that in a team environment it will only work if it is a rigoro开发者_开发知识库usly followed procedure.
Although I am not really interested in language specifics here, the language is C#.
Which would be better?
Thanks
If you were catching SettingsFileNotFoundException
on a different level (in a different, calling method) then it could make sense to create a custom exception because you might need to identify what exactly the error was. An over-simplified example is below:
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 searches for multiple settings files and thus has multiple throw ()
statements that use the exception. And the nested exception catching allows for all of those exceptions to be handled in the same way without putting the same code in your two secondary methods. Here, having your custom exception as a different type allows that particular exception to be handled in a way different than the rest of your error handling.
But assuming you aren't doing this fancy of error handling, the first approach you described is better because it is generalized. Why would you create an exception that could be thrown only once? I assume you are caching your settings in variables so you do not need to read your file every five seconds, thereby making the possibility of using the new exception limited to one time during the initialization of the application.
So in your case, unless you are very likely to expand your code to use more complex error handling in the future, you should probably just use a very specific message on a FileNotFoundException.
精彩评论