首页 > 解决方案 > 如何在不使用返回函数的情况下停止 Matlab 中的程序?

问题描述

我试图阻止下面的代码在程序的后面继续,但我不能使用return语句。例如,在下面的switch语句中,如果代码遵循该otherwise部分,我希望程序停止,而不使用returnorerror函数。

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 

标签: matlab

解决方案


如果您不想管理/传播特殊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:坏习惯,但如果你愿意,当然你可以把所有东西(即maindoSomething)放在一个例程中。


推荐阅读