Re: values for fields in failure/exception
On 12/9/2010 7:38 PM, Arne Vajh?j wrote:
On 09-12-2010 12:28, mark jason wrote:
In my program I need to return a result object as below
class MyResult {
private boolean success;
private double distance;
private String matchFileName;
private String message;
public MyResult (boolean s, double d, String mfn, String msg) {
this.success = s;
this.distance = d;
this.matchFileName = mfn;
this.message = msg;
}
//getters and setters...
}
In my program , I am returning a MyResult instance containing values
from a calculation.If an exception occurs ,I would like to return the
object with values which represent a failed calculation .The problem
is that,I cannot put distance as 0.0 since it is one of the valid
distance values.
So I put distance as Double.NaN.I don't know if this is the correct
way..Can someone suggest a better solution?
public MyResult getResult() {
MyResult res = null;
try{
res = calculate();
}catch(SomeException e) {
return new MyResult ( false, Double.NaN, "", e.getMessage() );
}
return res;
}
I think the whole concept is wrong.
You should not catch an exception and return an object
that by some magic values indicates and exception happened.
Let the exception propagate up to where the exception can be
really handled and avoid the magic values.
Sometimes you can do that, sometimes you can't, and sometimes
you don't want to.
The classic example of "can't" is when you're implementing an
interface and the interface's method lacks "throws SomeException".
If that's the case you cannot just let the exception propagate. Of
the many possible alternatives, three are common:
- Catch SomeException, wrap it in another exception (often an
unchecked one), and throw that instead
- Catch SomeException and "recover," perhaps by returning a
special value
- Catch SomeException and abort the program.
The third alternative is too draconian for most situations; the first
two are (IMHO) both perfectly viable, depending on the context.
--
Eric Sosman
esosman@ieee-dot-org.invalid