Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I throw an exception in Matlab?

I am writing some code and for now I am making some functions, but I'm not writing them yet. I'm just making an empty function that will do nothing yet. What I would like to do is throw an exception if the function is run, to prevent me from forgetting writing the function.

like image 272
Aaron de Windt Avatar asked Feb 18 '12 15:02

Aaron de Windt


3 Answers

The easiest way is:

error('Some useful error message.')

Matlab is happier is you assign an identifer to you error message, like this:

error('toolsetname:other_identifying_information','Some useful error message here.')

The identifying information is reported with some of the error handling routines, for example, try running lasterror after each of the above calls.

like image 160
Pursuit Avatar answered Nov 13 '22 15:11

Pursuit


You can also use:

  throw(MException('Id:id','message'));

There is a nice feature to MException, it can be used as sprintf:

  throw(MException('Foo:FatalError',...
  'First argument of Foo is %s, but it must be double',class(varargin{1}) )); 

As commented correctly by @edric, this sprintf functionality can be a double edged sword. If you use some of the escape characters, it might behave not like you want it.

throw(MException('Foo:FatalError',...
  'I just want to add a \t, no tab!' )); 
like image 29
Andrey Rubshtein Avatar answered Nov 13 '22 14:11

Andrey Rubshtein


Did you read the MATLAB documentation for "Throwing an exception"?

like image 1
Li-aung Yip Avatar answered Nov 13 '22 15:11

Li-aung Yip