Save output error messages to file in MATLAB

Doresoom picture Doresoom · Dec 17, 2009 · Viewed 15.1k times · Source

Is there a way to save MATLAB error messages to a file?

This may be a simple issue, but Google couldn't give me an answer. I've compiled a GUI executable for use without a MATLAB license, and occasionally it freezes. For aesthetic purposes, I suppressed the command window normally accompanying such an executable, so I can't get an error message out through the command prompt. I'd like to be able to create an error log which can be emailed to me for debugging.

Thanks!

Answer

Jonas picture Jonas · Dec 17, 2009

Use try...catch statements around the code. In the catch block, you can write out the error including stack information. Using sendmail, you can even have the code notify you of errors by mail (ideally with a popup that lets users decide whether they want to share the crash information with you)

try
   % your code here
catch err
   %open file
   fid = fopen('logFile','a+');
   % write the error to file
   % first line: message
   fprintf(fid,'%s\n',err.message);

   % following lines: stack
   for e=1:length(err.stack)
      fprintf(fid,'%sin %s at %i\n',txt,err.stack(e).name,err.stack(e).line);
   end

   % close file
   fclose(fid)
end 

Edited to be a bit more explicit on how to write error message to file