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

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.

Related

How do I make a dtrace probe only execute when a certain function is in the stack

OK, this is "fun." I'm trying to figure out a weird thread timeout in a program, and need to look at what is happening when pthread_cond_timedwait() returns on Solaris... But... Only when a certain wrapper function or functions are being called (call them foo_lock and foo_unlock)...
I don't think I can use this answer because the function I'm looking at is at least 2-3 hops up in the stack: dtrace execute action only when the function returns to a specific module
One of the weird behaviors is that I see the right parent in tracing entry, but not exit, when I use a return probe... This could be a buffering issue though. Have to dig...

PowerShell log all unhandled exceptions

I am looking to log unhandled exceptions, since my script runs as an automated tool with no one monitoring progress at the console. My thinking is to create my own exception class, which has a constructor that accepts [InvokationInfo] so I can then log the error with file and line number info, and possibly the trace stack as well. The goal is to catch as many exception types as possible and handle them, but have a generic final catch for exceptions that are literally my code failing. It occurs to me that the entire script would be one big try/catch so that literally anything I didn't expect (so long as it's terminating) would get caught and logged.
To that end I have this mocked up:
class UnhandledException : Exception {
UnhandledException () : base () {
}
UnhandledException ([System.Management.Automation.InvocationInfo] $InvokationInfo) {
Write-Host "Unhandled Exception in $([System.IO.Path]::GetFileName($InvokationInfo.ScriptName)) at line $($InvokationInfo.ScriptLineNumber)"
}
}
CLS
try {
1/0
} catch [System.IO.IOException] {
# Handled exception types go here
} catch {
$unhandledException = [UnhandledException]::new($PSItem.InvocationInfo)
#throw $unhandledException
}
This seems to be working well, and I am debating if that final throw is needed, or if I can just as well terminate the script from within the exception, since by definition once I have logged that info, and maybe thrown up toast message about the failure, I will be exiting the script anyway.
My question is, is this an appropriate way to handle exceptions when the script is functioning as a silent command line utility? I really don't want to have a situation where, if the console is showing, that powershell exceptions are visible. I want to handle everything, to the extent I can, quietly and with log files. Those logs could then be sent to me so I could troubleshoot.
That said, I have not found any info on wrapping the entire script in a try/catch. This
suggests that "catch everything" is a code smell, but it's also talking more about methods that are consumed by other users, not utility scripts.
The bit about std::uncaught_exception() sounds like it might be an option too, if I could have my regular log, for logging actual progress of the script and error in data, inability to access network resources, etc. All of which would be exceptions that I do catch and handle. If I could define a log file that is ONLY for otherwise uncaught exceptions that might be even better, but I also haven't found anything like that for PowerShell. So my approach is my backup plan. Unless I am missing something and this is a horrible idea?
And, to be clear, I am not thinking this would be the ONLY exception handling. This would be the handler of last resort, logging anything that I hadn't otherwise expected, planned for and handled.
EDIT: So, a limitation I have found to trap is that it still only traps terminating errors, and ideally I would like to also get a log of continued errors as well. To that end, I have been exploring redirects I have tried this
function LocalFunction {
1/0
}
&{
CLS
LocalFunction
Remove-Item 'Z:\no.txt' -errorAction silentlyContinue
Test-Path 'C:\'
Write-Host 'Continued'
} 2>> c:\errors.txt
This will successfully log the divide by 0 error in the function and the error at Remove-Item when -errorAction is Continue (the default), but when I specially set it to SilentlyContinue it isn't logged. This seems to get me where I want to be, with ANY error that would be seen in the console instead going to the text file. I could then, at the end of processing, test the size of that file, and delete if 0 or provide a toast message if something got logged.
The real question becomes, is the &{} construct around basically the entire script a viable option once it's a 10,000 line script, rather than a little example? And is it a good idea in general? Or is this perhaps something useful during development, but I just need to put on my big boy pants and actually HANDLE every possible error?
EDIT 2: Well, after doing some tests on a branch of my utility, this redirect approach is actually looking REALLY promising. Apparently no impact on performance, and I can even add the contents of my errors log to my regular log to make things easier for users. Curious if anyone has some counter indications?
Also, a little digging suggest that Invoke-Expression might be better, because the & operator creates a child scope, and that might cause problems while Invoke-Expression doesn't. But on the other hand Invoke-Expression is right up there with Regular Expressions in the "Don't do that" hierarchy. Things that make you go hmmmmmm?

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..

Get name of matlab file one step up in stack

I'm writing a matlab script where I'd like to know the name of the script which is one step up in the stack. The reason I need this is that I'm writing a helper script to be called to assert some basic facts about the workspace before engaging in heavier calculations, and the helper script should be able to give error messages when calling the calculation scripts.
I've tried using mfilename and dbstack, but I do not manage to get anything but the name of the helper script from them.
To explain further, I have the following scripts:
verify_base_conditions: the helper script, called on one of the first lines in
heavy_stuff_calculation and
sweet_mother_of_algorithms.
general_entry_point: a script where I gather common workflows in cells
I try to keep the entry point script as small as possible, and refactor heavier calculations (or anything that needs more than a few lines, really) into task-based, re-usable scripts. If I, from the entry point script, call sweet_mother_of_algorithms and the basic conditions for this script to run are not fulfilled, I want to see an error message like
Error: this_cool_var must be defined when running sweet_mother_of_algorithms
general_entry_point line 15
I tried using
error(['this_cool_var must be defined when running ' mdfilename])
and other similar constructs, but I couldn't make the error message say anything but verify_base_conditions.
How do I find the name of the script running one level up in the stack?
(Note: I'm not interested in finding the script running at the bottom of the stack - that will almost always be general_entry_point. I'm just interested in getting the name of the script that called verify_base_conditions.)
dbstack should work for this. I think this is an analogous set-up to yours:
a.m:
b;
b.m:
c;
c.m:
stack = dbstack;
for i=1:3
disp(stack(i));
end
When I run a;, this prints out the whole stack, including b (which I think it was you want - the second-top item on the call stack.
Alternatively, although this probably gives exactly the same result, you could throw and catch an error and look at its stack:
c.m:
try
error('What is on the call stack?');
catch e
for i=1:3
disp(e.stack(i));
end
end

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

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.