与 Python 一样,HALCON/Python 通过异常处理错误。如下例所示,HALCON 错误常量是在模块级别定义的。
def load_custom_pcb_img_or_fallback(custom_pcb_filename): try: return ha.read_image(custom_pcb_filename) except ha.HOperatorError as err: if err.error_code != ha.errors.H_ERR_FNF: # HALCON error code File not found. raise err return ha.read_image('pcb') img = load_custom_pcb_img_or_fallback('does-not-exist')
在本例中,我们希望加载自定义的 PCB 图像,或者在找不到图像时退回到默认的 PCB 图像。如果出现其他错误,我们希望将原始错误进一步向调用栈传播。
HALCON/Python 使用的自定义异常构成一个继承层次结构:
它从 HError 继承而来的标准 Python Exception 开始,然后是四个继承自 HError 的特定异常。它们出现在不同的情况下。算子和其他函数可能会引发不止一种异常。
class CustomClass(object): pass img = ha.read_image(CustomClass())
HALCON/Python 不知道如何将自定义用户定义类传递给 HALCON 算子 read_image。对于转换为或转换为本地 HALCON 元组失败的任何实例,都会引发 HTupleConversionError 实例。
所有自定义 HALCON/Python 异常都实现了 __str__ 。