10.8unwind_protect语句

Octave支持一种有限形式的异常处理,该处理模仿了无保护形式的Lisp。

的一般形式unwind_protect块看起来是这样的:

unwind_protect
  body
unwind_protect_cleanup
  cleanup
end_unwind_protect

这里的bodycleanup都是可选的,并且可能包含任何Octave表达式或命令。unwind_protect中的语句cleanup保证无论控制如何退出都能执行body.

这对于保护全局变量的临时更改不受可能的错误的影响非常有用。例如,以下代码将始终恢复全局变量的原始值frobnosticate即使在的第一部分出现错误unwind_protect

save_frobnosticate = frobnosticate;
unwind_protect
  frobnosticate = true;
  ...
unwind_protect_cleanup
  frobnosticate = save_frobnosticate;
end_unwind_protect

没有unwind_protect,的值frobnosticate如果在评估的第一部分时发生错误,则不会恢复unwind_protect块,因为计算将在错误点停止,并且不会执行恢复值的语句。

除了unwind_protect,Octave还支持另一种形式的感知处理try

版权所有 © 2024-2025 Octave中文网

ICP备案/许可证号:黑ICP备2024030411号-2