matlab - 如何在不使用返回函数的情况下停止 Matlab 中的程序?
问题描述
我试图阻止下面的代码在程序的后面继续,但我不能使用return
语句。例如,在下面的switch
语句中,如果代码遵循该otherwise
部分,我希望程序停止,而不使用return
orerror
函数。
case 1
rendevous = ('the Bridge');
case 2
rendevous = ('the Library');
case 3
rendevous = ('the River Crossing');
case 4
rendevous = ('the Airport');
case 5
rendevous = ('the Bus Terminal');
case 6
rendevous = ('the Hospital');
case 7
rendevous = ('St. Petes Church');
otherwise
disp('Decoy Message: Invalid Rendevous Point')
end
解决方案
如果您不想管理/传播特殊return
代码或值([]
例如)并立即停止,我会亲自使用一条error
语句,但使用特殊标识符并catch
在主调用函数中“隐藏”它(看起来这是你想要做的):
function [] = main(id)
%[
try
doSomething(id);
catch(err)
if (strcmpi(err.identifier, 'DecoyMessage:InvalidRendevousPoint'))
return; % Just leave the program without any error prompt (or add specific error handling code here)
else
rethrow(err); % Still raise other error cases
end
end
%]
end
function [] = doSomething(id)
%[
...
switch(id)
case 1, rendevous = ('the Bridge');
case 2, rendevous = ('the Library');
case 3, rendevous = ('the River Crossing');
case 4, rendevous = ('the Airport');
case 5, rendevous = ('the Bus Terminal');
case 6, rendevous = ('the Hospital');
case 7, rendevous = ('St. Petes Church');
otherwise, error('DecoyMessage:InvalidRendevousPoint', 'Invalid rendezvous point');
end
...
%]
end
这样,基于错误标识符,调用您的函数的人可以决定如何适当地处理它(抛出或不抛出或做特殊的事情)。
所有 matlab 内置错误和警告都有标识符,最好将标识符添加到您可能引发的自定义错误和警告中。这样,调用您的代码的人可以根据他们的意愿决定处理这些错误,或者暂时(或绝对)禁用这些警告,具体取决于他们是否认为合适。在以下链接中查看更多信息:
https://fr.mathworks.com/help/matlab/matlab_prog/respond-to-an-exception.html https://fr.mathworks.com/help/matlab/ref/warning.html#d122e1435922
PS:坏习惯,但如果你愿意,当然你可以把所有东西(即main
和doSomething
)放在一个例程中。
推荐阅读
- javascript - 如何动态地将 iframe 元素添加到 html 中?
- nestjs - 如何为`tsc-watch`注册`tsconfig-paths`?
- db2 - db2 HADR 环境中创建表空间问题
- prolog - 如何在 SICStus Prolog 中检查 WAM 代码
- django - 向 UserRegisterForm Django 添加额外字段(“城市”)
- linux - 如何在 .sh 文件中编写 ssh 连接代码以连接到远程机器
- javascript - 我无法自定义 epubjs-rn 中的突出显示颜色
- sql - 如何修复 sql-query 使混凝土部门去年销售的所有商品的价格翻了一番。甲骨文 SQL
- vb.net - 是否可以从 Dropbox 链接获取 .EXE 文件版本?
- c# - 将 Spritefont 分配到类中