I'm writing a procedure in Python which at it's fundamental level communicates with a motor controller. It is possible for the controller to throw flags indicating that an error has occurred. I'm trying to figure how to best handle these errors.
In the example below, there are three possible errors, a temperature fault, a current limit fault and a voltage fault. I've handled them differently. Is there a correct way or is it subjective?
class motor_fault(Exception):
def __init__(self,error):
motor.move_at = 0 #Stop motor
self.error = error
def __str__(self):
return repr(self.value)
motor.velocity_limit = motor.slow
motor.velocity_limit_enable = True
try:
motor.move_to_absolute = motor.instrument_pos
while motor.in_position == 0:
if motor.current_limit == 1:
motor.move_at = 0 #Stop motor
print('Motor current error')
break
if motor.temp_fault == 1: raise motor_fault('Temperature Fault')
if motor.voltage_fault == 1: raise voltage_fault:
time.sleep(0.5)
else:
print('reached desired instrument position with no faults')
except motor_temp_fault as e:
#Not sure what I'd do here...
print('My exception occurred, value:', e.error)
pass
except:
motor.move_at = 0 #Stop motor just in case
print(' some other fault, probably voltage')
else:
print (' this is only printed if there were no errors')
finally:
print ('this is printed regardless of how the try exits')
It seems a lot simpler to drop the whole try:
. Just set a flag in the while loop and break. After the loop, look at the flag and see if the while loop exited successfully.
fault = False
while motor.in_position == 0:
if motor.current_limit == 1:
fault = 'Motor current error'
break
if motor.temp_fault == 1:
fault = 'Motor temperature error'
break
if motor.voltage_fault == 1:
fault = 'Motor voltage error'
break
time.sleep(0.5)
else:
print('reached waterline with no faults')
if fault:
motor.move_at = 0 #Stop motor
print(fault)
# Now look at the fault string to determine the next course of action.
But that somehow seems wrong or non-pythonic to use a term I don't really understand. Is there really anything wrong with this? Thanks and please keep in mind I'm not CS major and I haven't taken a programming class since 1982.