Is `finally` block executed in case there is `return` inside a `try` or a `catch` block? - scala

Using a try-catch-finally construction to retrieve a database record, it seems that I need to return a value inside a try block in case everything was fine (as in case of an exception the end of the function is not meant to be reached). But If I return inside try, is finally code going to be reached (to close the connection etc.)?

Yes,
The result of the try/catch expression will be the last line of either the try or catch block, but the finally block will always execute no matter what

Yes.
The point of a finally is to ensure that some cleanup code is executed no matter what path the code uses to leave the try block. It happens on ordinary return, when an exception is thrown and caught, and when an exception is thrown that isn't caught by this try block. The only thing that will prevent it running is if the program is unable to leave the try block at all; an infinite loop inside it, or the process being killed by some means that prevents this normal processing from happening, or something of that order. I'm pretty sure even if you exit the process from inside the try block that the finally block will be executed before the process actually dies.

Related

Can a matlab function called within a script cause the script to break?

I am running a script which calls a function, and if a certain condition is met, inside the function, I want the whole thing just to terminate (and by that I do not mean I want to close matlab using exit). Is that possible? I know I can use return or break to return to the script, however I want the script to stop as well if this condition is met.
The only function I know of that does this is error. This throws an exception, and, if no exception handlers with try and catch are installed in the calling script, will terminate and return to command prompt. Which is what you want, as far as I understand. It prints an error message though. This could be suppressed if you guard all code in the top-level script with a try catch handler. However this will have to be specific to the one error and it makes debugging ("stop-on-error") much more difficult.
The thing is that the only use case I see for this behavior (termination of whole program on certain event) is when a non recoverable error occurs, and in that case printing an error message is indeed appropriate.
In case the script is successful termination of the whole program is not really the right way. All functions should return to give the upper layers of the code to perform some clean-up action, like saving the output data or so.

matlab can't catch error in subfunction

I'm trying to implement a bug reporting system in my code so I put a try/catch around the function that is run to start the program. It's a programmatic GUI so most of the subfunctions are callbacks for buttons or other GUI elements. However whenever an error is thrown in these subfunctions, it is not caught. Some of the subfunctions are defined in other files as they are other programmatic GUI files.
My question is, is there anyway to catch errors that are more than one function level deep?
Example below:
I run CeleST to start the program
function CeleST
try
% Global try-catch
CSTMainWindow()
catch exception
generateReport(exception) % bugReporter
end
CSTMainWindow is a programattic GUI file and here is one of the pushbuttons:
uicontrol('parent',mainPanel,'style','pushbutton','string','1. Process videos...','position',[500 yFilters+hFilters+10 170 60],'callback',#processVideo);
However errors in processVideo are not caught
processVideo:
function processVideo(hObject,eventdata) %#ok<INUSD>
set(mainFigure,'Visible','off');
CSTProcessVideos % Programmatic GUI File for another window
set(mainFigure,'Visible','on');
flagConsistentButton = false;
checkSequences
populateFilters
end
Even putting undefined variables in the subfunctions throws errors but they're not caught by my try/catch. Any suggestions or am I doing something wrong? Do I really have to put try-catch blocks around everything?
GTSMainWindow is not calling processVideo. Instead the function is used as a callback and called later.
Basically every callback function must care for it's own errors, put the try catch into the processVideo function and it will catch the error.

How is try catch evaluated in matlab?

I wonder how a try-catch block is evaluated in matlab. In particular, is the try-catch block evaluated in runtime or "compile time"?
Also, is a try-catch block expensive?
If someone have a link to any documentation that would be much appreciated.
(Btw, I know that try-catch is not the best solution in most cases. Still I would like to know how it works, since I have used it in some code).
try and catch blocks allow you to override the default error behavior
for a set of program statements. If any statement in a try block
generates an error, program control goes immediately to the catch
block, which contains your error handling statements.
To learn more about try and catch in Matlab:Try and Catch
Try and catch block is always executed in run-time and is used to catch the errors that occur and has error-handling statements. So if your code generates some error and you want to handle it, use it. Using error-handling is good programming practice..

How does NSLog solve optimization bug?

My app creates secondary thread by NSOperationQueue.
In main thread, it writes message in buffer which is global variable.
In secondary thread, it wait until message with new line character arrives.
It works well without optimization option.
It stays in while loop if I compile with any optimization option(-O1 ~ -Os).
But if I write NSLog inside loop, it works.
What is problem of this?
Is there better way I can solve this problem without using NSLog?
while (!strchr(buffer, '\n')) {
NSLog(#"!"); // without this, in optimized mode, it stays in while loop.
}
Your buffer is probably not declared volatile. The compiler can assume no one else changes buffer, and turn the loop into:
char* res = strchr(buffer, '\n');
while (!res) {}
which could be an infinite loop.
With an NSLog, the compiler cannot assume NSLog won't mess with the globals, so the condition isn't factored out.
If you want to wait for another thread to be ready, please at least use condition variable (NSCondition) instead of an infinite loop. Or maybe re-architect the code base to use GCD.

Can I have business logic in Finally block?

Is it advisable to have business logic in a finally block?
I have to send an email notification when a job is over (whether successful or not). Can I place the email logic in finally block?
The main danger I can think of is that the finally block has the ability to silently swallow exceptions and return values from the try block itself.
For example,
try {
doSomethingFancy();
} finally {
sendEmail();
}
If doSomethingFancy throws an exception, you will attempt to send an email. If somehow sending an email fails, sendEmail could throw an exception. This exception will "override" the original thrown one, and you'll never see it. It'll just vanish.
You could code around this defensively with more try / catch blocks, but just be aware...
Ideally you should have your business logic in Try block and Finally block should contain any cleanup task or any thing that must happen irrespective of success or failure of try block . You also need to make sure that the code in finally block does not cause any exception otherwise as Steven mentioned, the original exception will be lost if any.
You could do that in catch block in case if you intend to send error condition to designated email id. finally block is generally used for graceful-release of the resources mostly. I do not recommend sending email or performing any business rules within the finally block.
In my mind,
try {
doSomethingFancy();
catch(Exception ex) {
logError(ex);
}
sendMail();
Is the perfect pattern for this. Finally block should only be used to clean the mess the code in the try block could have left behind.