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.
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.
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!' ));
Did you read the MATLAB documentation for "Throwing an exception"?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With