Halcon算子翻译——try

名称

try - 开始一个程序分段,检测并捕获异常。

用法

try( : : : )

描述

  使用算子try,catch,endtry和throw可以在HDevelop中实现动态的异常处理,这相当于C ++和C#中的异常处理。 通过算子try,catch和endtry,形成两个代码分段:第一个分段(try.. catch)包含执行正常程序逻辑的被监控程序行。 第二个分段(catch .. endtry)包含在发生异常时运行的代码。

  算子try为下面的程序行启用异常处理,即,监控下面直到catch的代码块是否发生异常。 如果下面程序行的运行过程中发生错误或发生另一个异常状态,或者如果算子throw显式抛出异常,则try分段立即跳出(或者 - 取决于用户偏好 - 显示一个错误消息框),程序继续在相应的catch算子后运行。 如果在从try分段(直接或通过其他过程调用)调用的程序中引发异常,则try分段调用堆栈上的程序调用和所有中间过程调用立即中止(或者,如果适用的话,在显示错误消息框之后)。 If the exception is thrown within a procedure that was called from the try block (directly or via other procedure calls), the procedure call and all intermediate procedure calls that are on the call stack above the try block are immediatly aborted (or, if applicable, also after displaying an error message box).

  在抛出异常之前是否显示错误消息框由HDevelop首选项“Suppress error messages (throw directly an HDevelop Exception)”控制,可通过'Edit' - >'Preferences' - >'General Options' - >'Experienced User'。 这个消息框还提供了在抛出异常之前停止程序运行的时机,以便编辑可能的错误算子调用。

  监视异常的程序分段以相应的catch算子结束。 如果在监视的try分段内没有发生异常,则忽略下面的catch分段,并在相应的endtry算子后继续运行程序。

  每个try-catch-endtry分段可以互相嵌套,条件是在一个程序或不同程序调用中,任何内部的try-catch-endtry分段位于外部被嵌套的的try-catch或者catch-endtry分段内。 如果在一个内部try-catch分段内抛出一个异常,将被捕获到它本身相应的catch-endtry块中进行异常处理。 因此,除非通过从catch块中调用throw运算符显式地重新抛出异常,否则对于外部try-catch块,异常是不可见的。

  如果在HALCON算子中发生错误,则会创建一个异常元组并将其传递给负责捕获异常的catch算子。 元组收集有关错误的信息,如错误代码和错误文本。 捕捉到异常后,可以通过操作符dev_get_exception_data的帮助来访问这些信息。 有关传递的异常数据的更多信息,如何访问它们以及有关代码导出的注意事项,请参阅该算子的说明。 算子throw的说明描述了如何抛出用户定义的异常元组。

  HDevelop提供了禁止处理HALCON错误的机会。 这可以通过调用运算子dev_set_check('〜give_error')或取消选中对话框'Edit-> Preferences-> Runtime Settings'中的'Give Error'复选框来实现。 如果关闭了错误处理关,在发生HALCON错误的情况下,不会抛出异常,但程序继续正常运行。 与此不同的是,算子throw将始终抛出一个异常,与“give_error”设置无关。 如果在评估参数表达式期间发生错误,也是如此。

注意

  算子try,catch,endtry和throw不支持C语言导出,支持语言C ++,C#和VisualBasic / .NET。 只有后者支持跨程序抛出异常。

示例(HDevelop)

try
  read_image (Image, 'may_be_not_available')
catch (Exception)
  if (Exception[0] == 5200)
    dev_get_exception_data (Exception, 'error_message', ErrMsg)
    set_tposition (3600, 24, 12)
    write_string (3600, ErrMsg)
    return ()
  else
    * rethrow the exception
    throw ([Exception,'unknown exception in myproc'])
  endif
endtry

结果

  try总是返回2(H_MSG_TRUE)。

备选算子

  dev_set_check

See also

  catch, endtry, throw, dev_get_exception_data, dev_set_check

模块

  Foundation

HDevelop例程

try_catch.hdev          Demonstrate the usage of the exception handling in HDevelop
set_shape_model_timeout.hdev   Demonstrate how to use the timeout mechanism for shape-based matching
cancel_draw_result.hdev           Enable user-defined actions when a draw operation is canceled

原文地址:https://www.cnblogs.com/xhiong/p/7832405.html