我正在用 Python 编写一个程序,它在基本层面上与电机控制器通信。控制器可能会抛出指示发生错误的标志。我试图弄清楚如何最好地处理这些错误。
在下面的示例中,存在三种可能的错误:温度故障、电流限制故障和电压故障。我处理它们的方式不同。有正确的方法还是主观的?
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')
去掉整个似乎要简单得多try:
。只需在 while 循环中设置一个标志并中断。循环结束后,查看标志,看看while循环是否成功退出。
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.
但是使用我不太理解的术语似乎是错误的或非pythonic。这真的有什么问题吗?谢谢,请记住,我不是 CS 专业的,自 1982 年以来我没有上过编程课。