MATLAB: Error logging, MException messages get truncated

catchdiaryerrorlogMATLABmexceptiontry

I'm running a lot of separate functions on a lot of datasets. It's very time consuming and quite prone to errors so I devised the following set up in my code so I can see where things went wrong afterwards. Since the errors may occur in a sub function of a subfuntion, I embedded a small loop that loops through the stack of the MException block. Since I'm working with diary, I tried to display all information possible into the command window so it gets picked up in the log file.
function allAnalyses
logfilename = strcat('Log allAnalyses.m_',datestr(now,'dd-mm-yy HHMM'));
diary(logfilename)
tic
disp(strcat('Log van alleAnalyses.m_',datestr(now,'dd-mm-yy HHMM')));
try
disp('analysis_1');
analysis_1; % the function to employ
catch Error
warning('Error in analysis_1;')
disp(Error);
In_subfunction = Error.stack;
for i = 1:size(In_subfunction,1);
In_subfunction = Error.stack(i,:)
end
Reason = Error.cause
end
toc
% etc, 20 more blocks like this.
diary off
This results in text in the diary like:
Warning: Fout in analysis_1.m;
> In allAnalyses (line 110)
MException with properties:
identifier: 'MATLAB:xlsread:FileNotFound'
message: 'XLSREAD unable to open file '\\xxx\tools$\yyyy\Pro...'
cause: {0x1 cell}
stack: [1x1 struct]
In_subfunction =
file: 'C:\Program Files\MATLAB\R2015a\toolbox\matlab\iofun\xlsread.m'
name: 'xlsread'
line: 128
The problem here lays with the truncation of the message within the MException. Off course I need to know which file XLSREAD wasn't able to open. So how do I approach this?

Best Answer

  • Don't use disp to show the exception but make your own display, e.g:
    fprintf(' identifier: %s\n message: %s\n', Error.identifier, Error.message);
    Note that I don't show the cause and stack fields, since to properly display these you'd have to recurse through the cell arrays / structures.