Python Forum

Full Version: handle the error
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I communicate with device and receive data with this function:
def get_dcv(self):
    self.connector.send('DCV?')
    return float(self.connector.receive())
sometimes I can get broken data and I get "ValueError: could not convert string to float". How can I exclude and discard the given value and get another value?
I would start by understanding what is going on when the Value Error exception is raised. What is returned by receive()? Maybe start with something like this:
def get_dcv(self):
    self.connector.send('DCV?')
    try:
        value = self.connector.receive()
        return float(value)
    except ValueError:
        print(f"Expecting a float but got '{value}'")
    return 0
Now you can see what you get when this error occurs. Do the non-float return values contain important information?
(Nov-29-2021, 06:34 PM)deanhystad Wrote: [ -> ]What is returned by receive()?
returned values like: 1.0E3, 1.1E3 and so on., then I use this values for calculation.
The error occurs when the self.connector.receive () command receives an incomplete value. And I would like to clip it and get a different value instead.

(Nov-29-2021, 06:34 PM)deanhystad Wrote: [ -> ]Do the non-float return values contain important information?
No.
What do you mean by "clip it". When I hear that I think "clip the value to be inside some range".
just throw out this value
I would probably do something like this:
def get_dcv(self):
    self.connector.send('DCV?')
    try:
        value = self.connector.receive()
        return float(value)
    except ValueError:
        pass
    return None
If the get_dcv() returns a non-None value use it, otherwise ignore.

I don't like this as well, but it sounds more like what you are asking for:
def get_dcv(self):
    while True:
        self.connector.send('DCV?')
        try:
            return float(self.connector.receive())
        except ValueError:
            pass