Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
handle the error
#1
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?
Reply
#2
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?
Reply
#3
(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.
Reply
#4
What do you mean by "clip it". When I hear that I think "clip the value to be inside some range".
Reply
#5
just throw out this value
Reply
#6
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
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  how can i handle "expected a character " type error , when I input no character vivekagrey 2 2,762 Jan-05-2020, 11:50 AM
Last Post: vivekagrey
  Need suggestion how to handle this error farrukh 1 2,271 Dec-21-2019, 03:21 PM
Last Post: DeaD_EyE

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020