Is is possible to replace the following code with something which does not use exceptions? The handle x
is a provided handle. I want to test it for validity (having actual code to back the handle) before use.
x = @notreallyafunction;
try
x();
catch
disp('Sorry function does not exist.');
end
To test function handles such as for screening out the bogus
x=@notreallyafunction
in your question, you can use thefunctions
command to check the handle and get the referenced function's name, type (simple, nested, overloaded, anonymous, etc.), and location if it is defined in a file.The output of
functions
for a handle to a builtin (e.g.x=@round
) will look just like a bogus function handle (type
is'simple'
). The next step is to test the named function for existence:However, you need to deal with anonymous functions since they fail existence test:
The solution is to first check the
type
. Iftype
is'anonymous'
, then the check passes. If thetype
is not'anonymous'
, they you can rely onexist
to check the function's validity. Summing up, you could create a function like this: