Skip to Main Content

Java Programming

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Elegant way to return both a double and error notification from a method?

807580Mar 7 2010 — edited Mar 8 2010
I have a method that reads a value from a device and returns a double. The method is defined like this:
public class Device {
    // variables and stuff here.

    public double readValue() {
        double value = 0;
        try {
            // communicate with device here.
            // set value.
        } catch(Exception ex) {
            log.error(ex.getMessage());
            // tell parent I've failed somehow???
        }
        return value;
    }
}
...and is used like this (myDevice is an instance of the Device class):
double a = myDevice.readValue();
However I would really like to have a way of knowing if there has been an error. If my device has a read error how can I tell the parent class? I though of adding another parameter to the Device class like this:...
if (myDevice.errorStatus != 0) {
    // error!
}
...but obviously I can only call this after my readValue() has failed. Also, having readValue() return '0' to signify an error won't work, because zero may be a valid reading from the device. I cannot use a null value to signify an error either because I am not allowed to return a null double (compiler error). I feel that I'm going about this the wrong way. Can anyone please offer some advice? It's late and my brain is melting.

Many thanks,
MrQuan
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Apr 5 2010
Added on Mar 7 2010
24 comments
239 views