我试图阻止下面的代码在程序后面继续,但我不能使用return
语句。例如,在下面的switch
语句中,如果代码遵循otherwise
部分,我希望程序停止,而不使用return
或error
函数。
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
)。
鉴于您不能使用return
,您应该在这里使用,您可以改为执行更复杂的逻辑(正如贾斯汀在评论中首次建议的那样)。我不推荐它,但这是一个缺失return
的解决方法。
switch n
case 1
rendevous = ('the Bridge');
case 2
rendevous = ('the Library');
% other cases...
otherwise
% Illegal case
rendevous = [];
end
if ~isempty(rendevous)
% continue processing here...
end
在非法情况下,您将变量设置为特定的"错误条件"值,然后测试此条件以避免执行更多工作。您可以使用单独的error_condition
变量,在切换之前设置为false
,在非法情况下设置为true
,或者您可以使用您正在使用的变量,如此处rendevous
,设置为哨兵值,在本例中为空数组。