In my recent post on MExceptions, a user asked if a syntax error inside a function being called in a try/catch would get caught in older versions of MATLAB. I've done a tiny bit of investigation on this and report it here.
In this first example, I have an outright syntax error in my code.
1 function err1( 2 3 a = 3 4 b = 2
You can see that MATLAB can tolerate this, and indeed, seems to tolerate these sorts of errors in a try/catch context at least as far back as MATLAB version 5.3 (Release 11).
try err1 catch disp 'Landed in catch' end
Landed in catch
Similarly, for syntax that is not possible in MATLAB R2007b (the version used here), again the code jumps to the catch block. In the following code, you see that I try to index into the result of a function without assigning the function output itself to a variable. This is not something supported in MATLAB R2007b (and I have no statement to make about the future of this proposed construct except to say that it is an enhancement in our database and will be considered for the future).
1 function notPossibleR2007b() 2 3 a = eig(rand(3))(2)
try notPossibleR2007b; catch disp 'Got caught' end
Why might you wish to do this? One reason is if you are accepting user input or code for your application. If the code presented to you has something in it that won't work, you might still like to control the presentation of the error to your user. try/catch with the offending code in a separate file allows you to intercede and do just that.
Another reason to structure code this way is to allow you to take advantage of a new feature if it's available to your user. If not, do things the older, perhaps harder or more time- or memory-consuming way.
Do you need to "support" multiple versions of MATLAB? Will separating your code this way help? Let me know here.
Get the MATLAB code
Published with MATLAB® 7.5
To leave a comment, please click here to sign in to your MathWorks Account or create a new one.