MATLAB: Try/Catch Evalc and display output if error

evalcexceptionmastlab

Hi everyone,
I have a tricky question 🙂 I use evalc to call a function (which is not mine and which I don't to modify). But sometimes this function throws an error.
My problem is that the error message sent by this function is not explicit at all and all the details are in some text output before the error. And since I am in evalc I don't see these outputs. Is there a way of displaying that ?
small exemple :
  • the function that I can not to modify
function blackbox()
disp('explicit explanation');
error('see above');
end
  • my function
function my_code()
try
T = evalc('blackbox()');
catch
error(['oops: ' T]);
end
end
What I want is for my_code() to display 'explicit explanation'. But of course if I do what I wrote above, the T is undefined (because evalc/blackbox throwed an exception)
thanks for your help !
update: maybe it was not clear enough: but what I want is to get all the messages that were supposed to be displayed by the function that returned the error … and I can't find that in the ME …. In the example above, I want to be able to display 'explicit explanation'

Best Answer

Inefficencies and bad designs aside, for anyone who needs to solve the original problem, try the following:
% General Approach
exception = [];
output = evalc('try, someFunc(); catch E, exception = E; end');
% ... perform processing on 'output' and 'exception' (if not empty)
% Original Example Implementation
function blackbox()
disp('explicit explanation');
error('see above');
end
function my_code()
blackBoxException = [];
T = evalc('try, blackbox(); catch E, blackBoxException = E; end');
disp(T);
if ~isempty(blackBoxException)
disp(getReport(blackBoxException));
end
% Note: I'd recomend reformatting the getReport() output and either rethrowing it or displaying
% it as a warning. A few strsplit's and/or regexprep's can help with formatting.
The above would display the following:
>> my_code();
explicit explanation
Error using my_code>blackbox (line #)
see above
Error in my_code (line #)
T = evalc('try, blackbox(); catch E, blackBoxException = E; end');
>>