Aaron de Windt
Aaron de Windt

Reputation: 17708

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.

Upvotes: 6

Views: 8614

Answers (3)

Li-aung Yip
Li-aung Yip

Reputation: 12486

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

Upvotes: 1

Andrey Rubshtein
Andrey Rubshtein

Reputation: 20915

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!' )); 

Upvotes: 4

Pursuit
Pursuit

Reputation: 12345

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.

Upvotes: 6

Related Questions