How to test for errors on a function inputArgs
18 次查看(过去 30 天)
显示 更早的评论
I wrote the following function:
function feet2metersV2(altitudeValue)
%feet2meters converts feet to killometers and meters
% Version 2.0
if (length(altitudeValue)>1 || altitudeValue<0) %tests for user entering proper input
fprintf('You entered more than single input as altitude value or a non-positive value. \n')
else
% rest of my code
end % if block end
end % function end
If user call that function like this: feet2metersV2(3 4) or feet2metersV2() than MATLAB throws a build-in error.
I like to code a try-catch block for it in the function code. How do I address it? since it happens befor the code even starts. I am using a 2019a MATLAB version so I dont have the new 'argument validation' option.
Many thanks in advence.
0 个评论
回答(1 个)
Walter Roberson
2022-11-2
For the case of being called with no parmeters or too few parameters, you can use nargin() to test how many parameters were provided, and can do whatever is appropriate for the situation.
For the case of being called with too many parameters, then nargin() alone cannot solve the problem: MATLAB would normally detect the problem before entering the function at all. However, if you specify the last parameter name as the magic name varargin then MATLAB will permit any number of parameters, and you can then test nargin() to determine if too many parameters were passed. For example,
function feet2metersV2(altitudeValue, varargin)
if nargin < 1
%no parameters case
elseif nargin > 1
%too many parameters case
else
%right number of parameters case
end
end
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Function Creation 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!