Python Forum

Full Version: On error - go to the next task
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
There is a code that interrogates the device via modbus, in the code several devices are interrogated. When the device is turned off, there is no data, therefore an error is obtained and the program is closed, but the following devices can work. How to do that, if there is an error in the answer, then proceed to polling the next device?
Now I have done this:
request = client.read_holding_registers(62, 1, unit=0x01)
if request.isError():
    print('Modbus Error:', request)
else:
    result1 = request.registers
    written_as = result1[0] * 0.1
    print(f'{written_as:.1f}')
But this method is just going on to poll the next register. And upon reaching:
a1 =  float(result1[0] * 0.1)
    b1 =  float(row[2]) #row2- 1продукт
    silos13 = b1 - a1 - bool(b1 > a1) * 6553.5
    print ("Расход:"f'{silos13:.1f}')
I get:
Traceback (most recent call last):
  File "wl601.py", line 106, in <module>
    a1 =  float(result1[0] * 0.1)
NameError: name 'result1' is not defined
And the program closes
you want to use a try and except block
something like:
try:
    a1 =  float(result1[0] * 0.1)
    b1 =  float(row[2]) #row2- 1продукт
    silos13 = b1 - a1 - bool(b1 > a1) * 6553.5
    print ("Расход:"f'{silos13:.1f}')
except NameError:
    # add exception code here.
Thank you. The simplest and most important working solution. Big Grin