return statement after throw error in matlab - matlab

For my simple code It seems that the return statement is not needed after the error statement.
Does that mean the function would be early terminated once error is thrown?
If the above is true, what if i do want to process with the rest of function even after an error is thrown. For example, i can still compute c = a - b in my function.

Yes, the error terminates the program.
As suggested by Hoki, use a warning instead.
Note: Your function will throw anyway, if only modifying the code to use warning. This is because the return variable c is not assigned before after the if-statement.

Related

Exception/Error Handling in q kdb -- Alternative of Try-Catch-Finally(Java)/Try-Except-Finally(Python)

As we have try-catch in java, I can find trap-at in q kdb.
But my requirement is of try-catch-finally i.e in try block I'm opening odbc connection and in finally I want to close odbc connection.
Sudo code:
try{
con=openODBCConnection(dbName);
//n statements;
}catch(Exception e){
catchingNotSoImpException(e)
}finally{
closeODBCCon(con);
}
This is a fairly generic approach to using try-catch-finally logic in kdb, which separates out the try-catch, always runs the "finally" function. This returns the output if successful in either the try or the catch if necessary, or the error code if both try and catch have broken, allowing (potentially) more useful investigation and/or security on breaks:
tcf:{[t;c;f]
r:#[(1b;)value#;t;#[(1b;)c#;;(0b;)::]];
f[];
$[r 0;r 1;'`$r 1]}
The top line is the "try-catch" portion.
#[(1b;)value#;t;#[(1b;)c#;;(0b;)::]]
The function is called like so:
tcf[(tryfunc;1;`a);catchfunc;finallyfunc]
so the input has to be something that can be value'd in kdb - symbol, function and argument list, or string.
This can be used as-is, but for an explanation:
The key portion of logic here are the projections of (1b;) and (0b;) together with # on the value or c functions tell that operation to wait on input - so within the first part:
(1b;)value#
waits for the input t - if the value operation succeeds, (1b;correctOutput) is returned, i.e. the projection is executed.
If that fails, the error is passed to
#[(1b;)c#;;(0b;)::]
Which is basically the same thing, but instead of value, it uses the catch function, c. This is a projection which takes the input passed from the failed value before, then applies the same operations as above. Failed output is passed to a global null ::.
This ensures the data structure r has a leading 1b if either the try or catch was successful, and a 0b if both failed.
The finally function is then run, and the return is either the successful answer or a thrown error in the case of double failure.
Examples using similar definitions to Rahul's answer:
q)tryfunc
{x+y}
q)workingcatchfunc
{show "catch";100}
q)brokencatchfunc
{show "catch";1+`a}
q)finallyfunc
{show"finally"}
q)tcf[(tryfunc;1;1);workingcatchfunc;finallyfunc]
"finally"
2
q)tcf[(tryfunc;1;`a);workingcatchfunc;finallyfunc]
"catch"
"finally"
100
q)tcf[(tryfunc;1;`a);brokencatchfunc;finallyfunc]
"catch"
"finally"
'type
This works with functions taking any number of arguments also:
q)tcf[(monot;1);brokencatchfunc;finallyfunc]
"finally"
10
q)tcf[(monot;`);brokencatchfunc;finallyfunc]
"catch"
"finally"
'type
There is no finally block in KDB. One approach to get functionality closer to this in KDB is to write a function for final block and call it in both try and catch. This will not guarantee that this function will be executed always but will cover most of the cases.
q)finally:{show "finally"}
q)try:{show "try"; show x+y;finally[]}
q)catch:{show "catch"; finally[]}
q).[try;1 2;catch]
Output:
"try"
3
"finally"
Now, it is important where you call the finally function inside try and catch. The order of call could change the behavior. My suggestion is to call it at the last and always return result from finally function. If there is any return value from try or catch functions then pass that value to finally function. This will reduce the chances of errors, make code simple and also remove other overheads like call ordering issue.
Example of a return value from try block:
q) finally:{show "finally"; :x}
q) try:{show "try";r:x+y;finally r}
q) catch:{show "catch"; finally[]}
q) .[tyr;1 2;catch]
Output
"try"
"finally"
3

Test for one of multiple exceptions in Matlab unittests

I am using Matlab's unittest to test the handling of invalid parameters.
In the test I have a line
t.verifyError(#myObject.myMethod, 'MATLAB:nonStrucReference');
which works fine in Matlab R2014a, but fails in Matlab R2016a with the message
---------------------
Framework Diagnostic:
---------------------
verifyError failed.
--> The function threw the wrong exception.
Actual Exception:
'MATLAB:structRefFromNonStruct'
Expected Exception:
'MATLAB:nonStrucReference'
I wonder if it would be possible to test whether one of the exceptions is thrown.
I know that it would be possible to write
t.verifyError(#myObject.myMethod, ?MException);
but something more specific would be better.
You would likely want to write a custom verification method which accepts a cell array of exceptions as the input.
function verifyOneOfErrors(testcase, func, identifiers, varargin)
% Ensure that a cell array was passed rather than a string
if ischar(identifiers)
identifiers = {identifiers};
end
% If the function succeeds with no errors, then we want a failure
threw_correct_error = false;
try
func()
catch ME
% Check if the identifier is in our list of approved identifiers
threw_correct_error = ismember(ME.identifier, identifiers);
end
% Do the actual verification
testcase.verifyTrue(threw_correct_error, varargin{:})
end
Another alternative is to actually get the error message identifier dynamically within your testcase by explicitly causing the error, and retrieving the identifier.
% Get a version-specific identifier for this specific error
try; a = []; a.field; catch ME; end;
% Verify that your method throws this error
t.verifyError(#myObject.myMethod, ME.identifier)

Matlab: How can i stop a the whole function in matlab?

I have a function in matlab calculating something. Within that function I open another function to calculate something for it.
Now in this second function I have some case where I just want to stop everything if some certain condition is true (so I want to end both functions)
I don't want an error message or anything; Is there a command for that?
If I just type in error I get some notice in red with a message such as:
error: Invalid call to error. Correct usage is:
-- Built-in Function: error (TEMPLATE, ...)
-- Built-in Function: error (ID, TEMPLATE, ...)
error: called from:
error: /usr/share/octave/3.8.1/m/help/print_usage.m at line 89, column 5
>>>error: /home/john/wpq.m at line 75, column 4
error: /home/john/test.m at line 23, column 21
if I write error('blabla') I still get:
>>>error: blabla
error: called from:
error: /home/john/wpq.m at line 75, column 4
error: /home/john/test.m at line 23, column 21
I would like to get no output because I can write one line above already something like disp('the test on this number failed').
You could try placing a try/catch block in your main function to expect the condition under which you want code execution to stop.
I don't believe that there is any one command that allows code to stop execution from a function within a function.
There are a number of ways of doing what you want. Typically error is only meant to be used for things that actually is errors. You do for example get an "index out of bounds" error if you try to access an element outside the array. In case what happens is an error you should send an error message to inform users about what happens and highlight that this is an error. However, in case you only want this particular calculation to end and not the program I would instead recommend try-catch and printing the error message in catch.
In case this is normal termination (or if only a particular function terminates unnormally and this is expected for some input) you can either use a termination condition (function [out,success] = myFun(in)) or try-catch. Both are accepted, though I use to prefer the termination condition approach for normal termination and try-catch for unnormal termination (of functions). Unnormal termination can for example be when a function have to be terminated before all output variables are calculated. I use to prefer to have an exception thrown instead of a function returning invalid values (but a c-programmer would probably argue differently).
For the record, there is a return-statement in Matlab which terminates a particular function.
It is hard to recommend a particular approach without knowing the situation you are in, but this text would give you some different options to be choose between. Know that error handling seldom have standard approaches which can be said to be "right". It is often up to the programmer to decide what is suitable and that is typically a part of the design.
Good luck!

Can MatLab 'catch' be at higher level than 'try'?

Is it possible in MatLab to throw an exception in a nested function, and have it 'caught' by a higher up function, such as in C++ or Visual Basic?
It is quite possible to catch exceptions in a higher level then they occur. What I do not think works, is to catch exceptions on another level than where the try is. I am not sure about that though. The try catch is fairly simple to implement in matlab. It really solves itself in some auto- magical way. It is possible to throw exceptions inside try block and then it will be caught in the catch. It is also possible to just surround the code that may go wrong inside a try block and then catch the exception.
Using throw:
function mymain()
x=[1,2];
try
myfun(x);
catch me
disp(me);
error(me.message);
end
end
function myfun(x)
if (length(x)>1)
throw(MException('MATLAB:badsubscript','x must be scalar!'));
end
end
Using nothing:
function mymain2()
x=[1,2];
try
myfun2(x);
catch me
disp(me);
error(me.message);
end
end
function myfun2(x)
x(7);
end
The variable me is not defined in the sense that you yourself actually defines a variable me. It is rather matlab that creates an exception and then the exception is stored in the variable defined in the catch.

ILGenerator, make decision on return value of null

il.Emit(OpCodes.Callvirt, _compactBinaryReader_ReadObject);
this function is called and at a special condition a return value of 'null' is provided.
if that value is null i have to take a decision whether to jump on to a label or not
using after the method call
il.Emit(OpCodes.Dup);
il.Emit(OpCodes.Brfalse_S, DECISION);
gives me an exception "JIT Compiler encountered an internal limitation." when i call that function, the code builds correctly though.
tried OpCodes.Brfalse too.
what am i doing wrong ?
Found reasonS to the above problem,
one thing which should be understood that when an exception of
'CLR: Verification for Runtime Code Generation'
is thrown it means the code written is not in the correct format and when it is evaluated by the assembler it does not accept the written code, problem is usually because of stacks having extra values or less.
"JIT Compiler encountered an internal limitation." is thrown when at runtime it was expecting something else we provide something else in value or when stack has something else when something else was required.
In short, the later exception is thrown at runtime and the other is thrown when pre Run conditions are not met.
anyways i found the reason, i had some values still present on stack that i did not pop if Condition was met, so the POP OpCode did the trick, and by the way for me the Dup OpCode never worked out, it always pushes a null value on stack rather than duplicating the top most value.