Throw "out of range" in matlab - matlab

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.

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.

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

Related

MATLAB issue with Exception Handling

I am trying to handle exceptions gracefully such that when a user enters a character, when a number is expected, he is notified with a custom warning/message.
I know that the try, catch has the following syntax:
try
statements
catch exception
statements
end
I have been trying something like this, to no avail:
number = input('Enter number');
try
assert(isnumeric(number));
catch ME
warning('NOT A NUMBER');
end
I do not understand why the above code fails since assert if it is false, displays the error message 'Assertion Failed'.
I know that using try and catch is a bit of a sledgehammer approach, but I would like to understand how to implement the above functionality. Any tips would be appreciated.
From the help command:
input Prompt for user input.
RESULT = input(PROMPT) displays the PROMPT string on the screen, waits
for input from the keyboard, evaluates any expressions in the input,
and returns the value in RESULT. To evaluate expressions, input accesses
variables in the current workspace. If you press the return key without
entering anything, input returns an empty matrix.
Therefore if a user types in "goat" MATLAB will try to evaluate the variable named "goat". That is not helpful for this problem.
However looking further down the help command:
STR = input(PROMPT,'s') returns the entered text as a MATLAB string,
without evaluating expressions.
This is what is more applicable to your problem.
number = input('Enter number', 's');
try
assert(~isnan(str2double(number)));
catch ME
warning('NOT A NUMBER');
end

Is there a way way to generate a custom error message using narginchk in matlab?

Matlab is removing narchk function in future releases and I am trying to change some code to use narginck instead. Now with nargchk, the output was a string and I could pass it to an if statement to display my own error message. Something like
if ~isempty(nargchk(min, max, nargin))
error('custom error message')
end
narginchk automatically gives an error not a string, so I was wondering if there is a way to give a custom error message with narginchk
You cannot supply a custom error message to nargchk and related functions.
There is no need to use nargchk in your case since you don't need default values or anything, just simply check the value of nargin.
if nargin > max || nargin < min
error('custom error message');
end
Alternately, you could use assert to eliminate the if statement.
assert(nargin <= max && nargin >= min, 'Custom Error Message');
If you really want to use one of those functions, you could wrap it inside of a try/catch statement and provide a custom error message
try
narginchk(min, max, nargin)
catch ME
throw(MException(ME.identifier, 'my custom message'))
end

Preventing "MATLAB:unassignedOutputs" in Matlab

I'm looking to both catch and handle the "unassignedOuputs" error in Matlab. More specifically, looking at the following code:
try
[out1,out2]= somefunction(in1,in2);
catch err
if strcmp(err.identifier,'MATLAB:unassignedOutputs')
<some code>
else
rethrow(err);
end
end
If "somefunction" does not assign out2 and the resulting error is caught, is it possible to somehow retrieve the rest of the outputs from the function (in this case out1)? If not, is there a way to re-call the function ignoring that value so the function will not throw the error?
As far as I can tell, there is no way to retrieve variables once the function has been terminated with this error. For the case when the first output is produced but not the second, you could retry it with just one output, naively something like:
try
[out1,out2]= somefunction(in1,in2);
catch err
if strcmp(err.identifier,'MATLAB:unassignedOutputs')
try
out2 = [];
out1 = somefunction(in1, in2);
catch err2
% rethrow original error
rethrow(err)
end
else
rethrow(err);
end
end
To display a message saying which output wasn't assigned, you'd have to parse err.message (although the default message itself should be reasonably clear).
But getting this to work if you have more than two outputs, and you don't know which might have not been properly defined, would not be simple. And if the first output is not defined, this won't work at all. In that case you would have to, I think, edit the function itself.
If the specific use case is checking a bunch of student codes which all take the same inputs and provide the same outputs, an alternative option would be to provide them with a function template which contains a check at the end if the outputs exist, and if not sets them to empty and displays your custom message.

Matlab: How to catch warning

I am running some data processing work in MATLAB and solver uses BACKSLASH operator. Sometimes, I get warning like this:
Warning: Rank deficient, rank = 1390, tol = 1.335195e-010.
Warning: Rank deficient, rank = 1386, tol = 1.333217e-010.
I would like to catch those warnings.
I am trying to convert warning to error and then catch it as described here under title “Trapping warnings”:
http://undocumentedmatlab.com/blog/trapping-warnings-efficiently
In the example, following string has been used to convert warning to error:
s = warning('error', 'MATLAB:DELETE:Permission');
However, I am not sure what string to use for my case. I tried using
s = warning('error', 'Warning: Rank deficient’);
But, it did not work.
Any help would be appreciated.
Regards,
DK
You need to specify the warning identifier, not the warning text. You can find the identifier using the two-output form of lastwarn:
[msgstr, msgid] = lastwarn
In your case, I think the identifier you want is 'MATLAB:rankDeficientMatrix'.
You could try to use lastwarn as an alternative. After your division, call it and compare it with strcmp to the usual warning message, and if its the one you wnat you could manually throw the error you want with error.
As you suggested: you can reset lastwarn throwing an empty warning warning('')

How to get the sql state from libpq?

I program with libpq.so. I want to get the error code which is called sql state in SQL Standard.How should I get this in my c code?
The obvious Google search for libpq get sqlstate finds the libpq-exec documentation. Searching that for SQLSTATE finds PG_DIAG_SQLSTATE in the PQresultErrorField section.
Thus, you can see that you can call PQresultErrorField(thePgResult, PG_DIAG_SQLSTATE) to get the SQLSTATE.
This is just addition I can not leave in form of comment due to reputation reasons.
Note that you can not portably get SQLSTATE for errors that can occur during PQconnectdb. In theory, you can read pg_conn (internal struct) field last_sqlstate which contains correct value.
For example, if you try to connect with invalid login/password, it will give you 28P01. For wrong database it will contain 3D000.
I wish they defined publically available getter for this field.
You can check this one as well:
libpq: How to get the error code after a failed PGconn connection