Entry
what's the difference of exceptions and return parameter?
Oct 28th, 2004 12:01
Tom McGuire, bill au,
Exceptions and return parameters are apples and oranges.
Take this method for example:
EXAMPLE 1:
int getStringLength(String str) throws IllegalArgumentException{
if(str==null){
throw new IllegalArgumentException("String must not be null");
}
return str.length;
}
Where the following keywords/tokens are defined:
"int"-- The return type. This specifies the type of information which
(under normal circumstances) is guaranteed to be returned by the method
invokation. In this case, the "getStringLength" method will return an
integer unless something exceptional occurs.
"throws" -- The "throws" keyword is used to declare a list of
Exceptions which may be thrown when the method encounters an
exceptional condition from which it cannot recover sufficiently to
return a meaningful value.
The above provides insight into the core difference between a return
value (parameter) and an exception: Return values are provided when
things go well; Exceptions are used when things go poorly.
It is important to note that Exceptions are not required. The above
method could be written like this:
EXAMPLE 2:
int getStringLength(String str){
if(str==null){
return -1;
}
return str.length;
}
Why would you choose one over the other? The best answer I can provide
is this: Look at the design conventions currently in use within your
software, and do the same. If there is no precidence to follow then
consider how the method will be invoked and what you would have to do
as the caller. For instance:
If you had to call the code in example 1, you would do something like
this:
(Given a String called "aString")
int aStringLength = 0;
try{
aStringLength = getStringLength(aString);
//at this point, you have successfully recorded the length
}catch(IllegalArgumentException iae){
//aString is null, so now what do you do?
}
Compare that with the following code which uses example 2's
implementation:
int aStringLength = getStringLength(aString);
if(aStringLength==-1){
//you know that aString is null.
} else {
//you know that aString has a valid length...
}
As you can see, the decision to use Exceptions affects both the method
implementation and the method invokation.
So why use exceptions? Because it is frequently the case (especially in
lower-level application logic) where you encounter a situation where
there is no "correct" action. Throwing an exception is the equivalent
of "punting the ball" and hoping that the caller will know what to do.
When deciding whether or not to throw an exception, you should take
into accound the runtime performance of declaring an exception. It's
not much, but there is overhead involved. Declaring exceptions too
frequently is a bad practice and will result in slower code execution.
You should also avoid the practice of "programming by exception" where
you rely exceptions being thrown to determine the logical flow of your
application.