Loren on the Art of MATLAB

Turn ideas into MATLAB

Note

Loren on the Art of MATLAB has been archived and will not be updated.

How to Safely Try Unknown Code

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.

Contents

Syntax Error is Caught

In this first example, I have an outright syntax error in my code.

dbtype err1
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

Unsupported Syntax

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).

dbtype notPossibleR2007b
1     function notPossibleR2007b()
2     
3     a = eig(rand(3))(2)
try
    notPossibleR2007b;
catch
    disp 'Got caught'
end
Got caught

Why?

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.

Thoughts?

Do you need to "support" multiple versions of MATLAB? Will separating your code this way help? Let me know here.




Published with MATLAB® 7.5


  • print

Comments

To leave a comment, please click here to sign in to your MathWorks Account or create a new one.