【问题标题】:Throw "out of range" in matlab在matlab中抛出“超出范围”
【发布时间】:2014-05-23 18:19:41
【问题描述】:

我有一个案例,我想在 matlab 中抛出一个超出范围的异常,但也给出了向量超出范围的原因(向后兼容性不好)。当然可以有某种fprintf()... error('out of range')。但是,感觉这里走对路可能会很好,因为

try
    a = b(c);
catch err
    throw(err,'Identifier');
    error('lack support for particular case');
end

问题是:如何创建err?;还有:matlab 中调用的“超出范围”的标识符是什么?

错误消息不同的原因是因为对于fprintf 情况,不应仅使用注释传递超出范围。

【问题讨论】:

    标签: matlab throw


    【解决方案1】:

    在声明中

    try
       doSomethingThatMayResultInError();
    catch me
       doSomethingWithTheError(me);
    end
    

    meMException 类的对象,其中包含错误的所有信息,包括堆栈跟踪。

    如果您想在抛出的错误中添加其他信息,可以通过以下方式进行:

    try
       doSomethingThatMayResultInError(a,b);
    catch me
       %# throw a more easy-to-understand error
       error(['This use case, i.e. with length of a (%i) different from length of b (%i)'...
              'is not supported. Error details: %s'], length(a), length(b), me.message)
    end
    

    当然,您可以通过添加例如带有错误标识符 (me.identifier) 的 switch/case 语句,尽管您应该知道错误标识符在最近几个版本的 Matlab 中已经更改了几次。

    【讨论】:

    • 谢谢。正是我想要的。这将给出标准错误和自定义解释,可为其他用户节省大量时间。
    【解决方案2】:

    我不确定您所说的“如何创建me?”是什么意思,它是在抛出错误时为您创建的。至于检查标识符,为什么不自己抛出错误并检查 me 对象(虽然我认为 me 是一个坏名字,所以我将使用 err 代替):

    try
        a = b(c);   %// making sure that the error you want occurs!
    catch err
        disp(err.identifier);
    end
    

    【讨论】:

    • 使用err 确实有意义,谢谢。并为“抛出错误时创建消息”+1
    猜你喜欢
    • 2012-05-04
    • 2022-06-14
    • 2020-01-29
    • 1970-01-01
    • 2013-11-18
    • 2013-09-28
    • 2012-09-20
    • 1970-01-01
    • 2019-04-25
    相关资源
    最近更新 更多