As software developers we make dozens of design decisions daily, some are more subtle than others. Recently, I briefly reconsidered returning error values instead of exceptions to signal error conditions.
As a general rule my policy is to throw exceptions except when I’m the only consumer of the method and if I am the only consumer of the method it is sometimes OK to return a BOOLEAN value to signal success or failure.
The obvious reason to avoid exceptions is that they are invisible in the source code, especially in C#. Looking at a block of code there’s no way to see which exceptions will be thrown and from where. Exceptions also create too many exit points from your function, and as a programmer you must be aware of all of them. Finally, your program takes a small performance hit when you use exceptions because exceptions throw off the stack frame.
I’m still inclined to continue using exceptions. Anyone who has worked on applications with several developers knows how difficult it is to maintain functions that return error values– as the program grows developers add new return values and it’s not easy to determine which error value corresponds to which error condition. Using return values to indicate errors leads to software that is more difficult to maintain.
Exceptions also force the caller of your method to deal with the exception, it is very easy to ignore return values, and an unhandled exception will stop your program from executing. Additionally exceptions let the developer choose where the error should be handled. Code can be written to catch exceptions near the failure point, or further up the stack. With return values your error handling code must be near the point of error; often the mechanism to deal with the error (i.e.: the user) is not available at the point of failure.
This being said, I’m not advocating throwing generic exceptions, you as developer must consider how your code will be used and throw exceptions which properly convey the type of errors your method may encounter.
Using exceptions instead of returning error values allows your program to be more flexible and easier to maintain, I can’t think of any good reasons to stop using exceptions. What are you opinions?