MatLab 'catch' 能比 'try' 更高吗?

Can MatLab 'catch' be at higher level than 'try'?

在 MatLab 中是否可以在嵌套函数中抛出异常,并由更高级的函数(例如在 C++ 或 Visual Basic 中)使它 'caught'?

很有可能在更高级别捕获异常,然后再发生。我认为行不通的是在尝试所在的另一个级别上捕获异常。不过我不确定。 try catch 在 matlab 中实现起来相当简单。它确实以某种自动神奇的方式自行解决。可以在 try 块中抛出异常,然后在 catch 中将其捕获。也可以只将可能出错的代码包围在 try 块中,然后捕获异常。

使用投掷:

function mymain()
    x=[1,2];
    try
        myfun(x);
    catch me
        disp(me);
        error(me.message);
    end
end

function myfun(x)
    if (length(x)>1)
        throw(MException('MATLAB:badsubscript','x must be scalar!'));
    end
end

什么都不用:

function mymain2()
    x=[1,2];
    try
        myfun2(x);
    catch me
        disp(me);
        error(me.message);
    end
end

function myfun2(x)
    x(7);
end

变量me并不是你自己定义的变量me。而是matlab创建异常,然后将异常存储在catch中定义的变量中。