I was recently told that I'm abusing exceptions to control the flow in my applications, so I this is my attempt to somehow clarify the situation.
To my mind, a method should throw an exception, when it encounters a situation, which can't be handled internally or might be handled better by the calling side.
So - does any particular set of rules exist, which can be used to answer the following set of question when developing your applications:
When should I throw an exception and when should I write code with strong nothrow guarantee, which might simply return
bool
to indicate success or failure?Should I try to minimize the number of situations, when the method throws an exception or , on the contrary, should it be maximized to provide flexibility when handling these situations?
Should I stick to the exception throwing convention set by the frameworks / runtimes I use when developing my applications or should I wrap all these calls so that they match my own exception throwing strategy?
I was also adviced to use error codes for error handling, which seems pretty efficient, but ugly from the syntactical point of view (also, when using them a developer loses the ability to specify the output for a method). What do you think about this?
Example for the third question (I was using an I/O framework and encountered the following situation):
The described framework does not use exceptions to handle errors, but the other code does use them. Should I wrap every possible failure indicated with
'???'
and throw an exception in this case? Or should I change the signature of my method tobool PrepareTheResultingOutputPath
and only indicate whether the operation was successful or not?
public void PrepareTheResultingOutputFile(
String templateFilePath, String outputFilePath)
{
if (!File.Exists(templateFilePath))
// ???
if (!Directory.MakePath(outputFilePath))
// ???
if (File.Exists(outputFilePath))
if (!File.Remove(outputFilePath))
// ???
if (!File.Copy(templateFilePath, outputFilePath)
// ???
}
Another example - even the .NET Framework
doesn't follow some strict exception throwing strategy. Some methods are documented to throw 10+ different exception types, including trivial exception types like NullArgumentException
, but some of them simply return bool
to indicate success or failure of the operations.
Thank you!