How to display errors in GUIs

When you design a set of GUIs in Matlab, you basically want to provide the user with a complete control over your code with a simple window. But often, one concern is that you need to take care of misfiled field in your interface. For instance, let’s suppose you ask your user to set a particular string to a number. If that user doesn’t fill a number but a letter, your program will crash.

This is often a discouraging thought for developers as they need to think in advance of all the possible outcome of the interface and restrict the possibilities to only what is meaningful to the code. This is especially bad for Matlab (as compare to Labview) as Mathworks did not implement controls that only works with numbers.  So one has to make a checkup for every single string field.

I propose here an easy work around to this issue. It won’t completely solve the errors but at least it will provide a direct feedback to the user that he did something wrong, like on the following picture.

Usually, most GUIs have one or two buttons that actually perform the job.

I suggest you use the following code in your callback.

try

%%%%%%%%%%%%%%%%%%%%%%%%%%%
%                         %
%   PUT YOUR CODE HERE    %
%                         %
%%%%%%%%%%%%%%%%%%%%%%%%%%%

catch errorObj
% If there is a problem, we display the error message
errordlg(getReport(errorObj,'extended','hyperlinks','off'),'Error');
end

When you start your callback, it ‘tries’ it and if an error occurs, it goes to the catch block. the errorObj is a standard matlab class that stores all the information about the error. You can actually adjust the response depending on the error message. This code will reroute the error message from the command line to a nice error window. Most of the time, the error is clear enough that you can tell what happened.
The hyperlinks option is to remove the http link that is always added to error message. They don’t work in matlab figures.

This entry was posted in Intermediate, Making interfaces. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *