Exceptions vs. Return Values
I'm implementing someone else's design. The designer chose to use int return
values to indicate success/failure on methods. I mentioned that with .NET
it might make more sense to use exceptions. The designer agreed until he
read this paragraph from the MSDN article "Exception Management in .NET"
by Kenny Jones and Edward Jezierski.
"You should only throw exceptions when a condition outside of your code's
assumptions occurs. In other words, you should not use exceptions as a means
to provide your intended functionality. For example, a user might enter an
invalid user name or password while logging onto an application. While this
is not a successful logon, it should be a valid and expected result, and
therefore should not throw an exception. However, an exception should be
generated if an unexpected condition occurs, such as an unavailable user
database. Throwing exceptions is more expensive than simply returning a result
to a caller. Therefore they should not be used to control the normal flow
of execution through your code. In addition, excessive use of exceptions
can create unreadable and unmanageable code."
This parapraph implied to the designer that he really should still have a
return value to handle "normal" cases to indicate success/failure.
I don't disagree with the paragraph in the article, but with the interpretation
of the designer I'm working with. Now I'll have methods that throw exceptions
AND return success/failure which I think will confuse the developers who
are trying to use my methods. It means they will still have to check return
values after every method call, defeating the whole point of having exceptions.
If I'm forced to implement this design, it makes more sense to me to catch
all exceptions in my code with a generic exception handler and then in the
catch block just return 0. That way I'm at least consistent.
Here is the specific scenario if it help.
We will have a central app that other apps have to register with by using
remoting and calling a Register method. Periodically the apps need to CheckIn
otherwise they will be marked as being off line. Both of these methods have
return values of int to signify if the call was successful. Does this make
sense? To me it seems a perfect example of when to use exceptions. Then
the client app can make the method call and assume everything is fine unless
an exception is caught.
Top DevX Stories
Easy Web Services with SQL Server 2005 HTTP Endpoints
JavaOne 2005: Java Platform Roadmap Focuses on Ease of Development, Sun Focuses on the "Free" in F.O.S.S.
Wed Yourself to UML with the Power of Associations
Microsoft to Add AJAX Capabilities to ASP.NET
IBM's Cloudscape Versus MySQL