我正在用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年以来我就没有上过编程课。
发布于 2010-12-30 05:45:41
无论如何,我的方法是定义一个小的异常层次结构,比如:
class MotorFaultError(Exception) # top level exception
class MotorTempFault(MotorFaultError)
class MotorVoltageFault(MotorFaultError)
# etc然后,如果出现任何错误,请确保您的API抛出其中一个错误。如果您的API本身必须从底层的引擎API捕获异常,请将该异常包装在您自己的一个异常中。
基本原理:
您自己的异常层次结构是API的一部分,用于将调用代码与底层引擎API的细节隔离。通过抛出一组已定义的异常,而不是允许引擎API的异常冒泡,您可以进一步隐藏底层API。这样做可以更容易地将另一个引擎API放在适当的位置,无论出于什么原因,包括:
此外,异常(而不是标志)与其他Python API的行为方式更一致。
发布于 2010-12-30 05:33:07
我会使用许多例外子句来处理您现在想要处理的所有不同的异常,因为这些情况似乎是异常/失败场景。
我不会使用标志来表示这些场景,因为它会向引擎添加更多的字段,而这些字段在这个用例之外似乎没有用处/相关性。
就知道这是否是处理好这个问题的“正确”方法而言,如果两个解决方案都有效,那么它们都是正确的!
希望我说得够清楚了..。;-)
发布于 2010-12-30 05:36:28
我认为这两种方法都没有错。就我个人而言,我更喜欢尝试--除了一个,但这只是我的偏好。
https://stackoverflow.com/questions/4557970
复制相似问题