小编AE4*_*082的帖子

在MATLAB中将警告转换为错误

在我的一些函数中,我想将一些警告转换为错误.例如,如果我想在str2func产生MATLAB:str2func:invalidFunctionName警告时抛出错误,我会执行以下操作:

invalid_func_id = 'MATLAB:str2func:invalidFunctionName';
%hide warning of interest
warning('off', invalid_func_id);
%this might yield the warning of interest
predicate_func_try = str2func(predicate_func);
[~, warn_id] = lastwarn;
assert(~strcmp(warn_id, invalid_func_id)...
    , 'MyFunc:InvalidFunctionName'...
    , 'The predicate function %s does not have a valid name'...
    , predicate_func...
    );
warning on all
Run Code Online (Sandbox Code Playgroud)

如果我知道特定的代码块可以提供一小组警告,那么这种方法很好.但是它很冗长,可能无法扩展到更大的代码块.有没有更好的方法呢?理想情况下,我想要一个可以将某些警告转换为整个块中的错误的函数.它允许我将我的例子修改为:

warnings2errors('MATLAB:str2func:invalidFunctionName');
predicate_func_try = str2func(predicate_func);
warnings2errors('off');
Run Code Online (Sandbox Code Playgroud)

error-handling matlab warnings

8
推荐指数
2
解决办法
2631
查看次数

取消MATLAB对象构造没有例外?

在我写的MATLAB类中,如果构造函数被赋予0参数,则要求用户使用提供文件uigetfile.如果用户取消提示,则uigetfile返回0.在这种情况下,制作对象毫无意义.有没有办法在不抛出异常的情况下取消对象构造?如果我提前返回,我会得到一个无法使用的格式错误的对象.这是代码的样子:

classdef MyClass
    methods
        function self = MyClass(filename)
            if nargin == 0
                filename = uigetfile;
                if filename == 0
                    %cancel construction here
                    return; %I still get a MyClass object with self.filename == []
                end
            end   
            self.filename = filename;
        end
    end

    properties
        filename;
    end
end
Run Code Online (Sandbox Code Playgroud)

但是我不确定uigetfile在构造函数中使用是否正确.也许它应该是我的代码的另一部分的责任.

oop matlab

3
推荐指数
1
解决办法
289
查看次数

标签 统计

matlab ×2

error-handling ×1

oop ×1

warnings ×1