Typically when using Matlab, if the program encounters some bug, you will hear the system bell and see the dreaded red text show up in the command window. So what do you do if you absolutely need your programs to run without error? Having a program crash is unacceptable. You must implement error handling within your code.
Error handling is just as it sounds – a way for your program to respond when it encounters an error. A common error handling technique is to use try and catch blocks.
The basic way it works is the following:
- Your program attempts to run code in the try block
- If an error occurs, control of your program is given to the catch. If no error occurs, the program will skip over the catch
Here is the general syntax:
try % The statements you wish to try catch exception % What to do if an error occurs end
- Be sure to note that under the try block, you can put as many statements as you wish. If an error occurs for any of them, control of the program will be given to the code within the catch block.
- You can nest try and catch blocks. For instance, if an exception is thrown (i.e. an error occurs in your try block), you can put a second try and catch block within your original catch block. In essence, you can try issuing some command and if that doesn’t work, you can try another command in a second try/catch block located in the original catch block
- In the above snippet, the variable exception is optional. By placing a variable here, you will create an exception object, which stores information about the error you have received. Leaving the space next to catch blank will simply give control to the catch block of code, but no information about the error will be retained.
To give a brief explaination of using a try/catch block, I will provide you with an example where I need to read in an MS Excel file. I am looking to make this process as user friendly as possible, so I would like the user to select the correct Excel file using a GUI. Meanwhile, I need to ensure that the program does not report an error when the user cancels out of the select file GUI. I also want to ensure that the user selects a file in the current directory.
% Open UI window to get file - limit to only .xlsx files [FileName,PathName] = uigetfile('*.xlsx','Select your Excel file'); try % try to read in Excel file vals_from_excel = xlsread(FileName); catch exception if strcmp(exception.identifier,'MATLAB:xlsread:InvalidFileName') disp('You MUST choose one file in the current directory') disp('Exiting without completing...') break; % break the program without showing error elseif strcmp(exception.identifier,'MATLAB:xlsread:FileNotFound') disp('The selected file was not in the current directory') disp('Exiting without completing...') break; else % Unexpected error - display the result disp(exception.identifier) error('An unexpected error has occured') end end
By taking advantage of the exception variable, we are able to give very specific instructions to the end user when they do something that is not intended. If the program does not see an error that we intend, it will simply fall through to the last else and will give the user the error that Matlab reports.
You will notice in the above script the use of exception.identifier. When control is given to the catch block, the exception object gets created with four properties:
- identifier: identifies the error that occurs
- message: the string that would be displayed had we let program run without try/catch
- stack: a path to find where exactly the error occurred. This is helpful for determining errors within multiple sub-functions.
- cause: the cause of the error
The reason for using the identifier property in load_specified_excel.m is to allow the developer to make very useful suggestions to the end user about how to use their programs. In order to do this, however, you will need to previously know the error identifier for a specific message. You can do this by running your program then committing some error, and finally exploring the exception object. By looking at the identifier property within your exception object, you will know exactly the string produced when this certain type of error is committed.
A few more helpful things about the above script:
- Using the syntax above for the uigetfile() function, we can limit the file format to only accept .xlsx files
- It is not necessary to use the breaks here, but something like this may be useful if it were a longer program that depended on input from that Excel file.
- If an error occurs that we have not expected (i.e. we have not already planned for), we would like to throw an error. To do this, we simply use the error(‘Your custom error here’) command. This will throw a custom error message and can be used to provide your end user with more information about how to properly use your code and prevent errors in the future.
Writing better code means writing code that will break less often. Ideally, the code is able to take care of any errors that may occur during its execution and using try/catch blocks is a nice, simple way to accomplish this task.