How to test for errors on a function inputArgs
18 views (last 30 days)
Show older comments
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 Comments
Answers (1)
Walter Roberson
on 2 Nov 2022
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 Comments
See Also
Categories
Find more on Function Creation in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!