Question

I have a case where I want to throw an out of range exception in matlab, but also give the reason to why the vector goes out of range (bad backward compatibility). It is of course possible to have some kind of fprintf()... error('out of range'). However, it feels like it may be good to go the proper way here, as

try
    a = b(c);
catch err
    throw(err,'Identifier');
    error('lack support for particular case');
end

The question is: How to create err?; And also: What is the identifier for "out of range" called in matlab?

The reason that the error message is different is because for the fprintf case the out of range should not be passed with only a comment.

Was it helpful?

Solution

In the statement

try
   doSomethingThatMayResultInError();
catch me
   doSomethingWithTheError(me);
end

me is an object of class MException that contains all information, including stack trace, of the error.

If you would like to add additional information to the error you're throwing, you can do it the following way:

try
   doSomethingThatMayResultInError(a,b);
catch me
   %# throw a more easy-to-understand error
   error(['This use case, i.e. with length of a (%i) different from length of b (%i)'...
          'is not supported. Error details: %s'], length(a), length(b), me.message)
end

Of course, you can make error handling more involved by adding e.g. switch/case statements with error identifiers (me.identifier), although you should be advised that error identifiers have been changing a few times in the last few versions of Matlab.

OTHER TIPS

I'm not sure what you mean by 'how to create me?', that gets created for you when the error is thrown. As for checking the identifier, why not just throw the error yourself and inspect the me object (although I think me is a bad name so I'm going to use err instead):

try
    a = b(c);   %// making sure that the error you want occurs!
catch err
    disp(err.identifier);
end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top