Is there a way to define a callback function in Matlab that triggers on runtime errors?
50 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
I am wondering if there is a way to create a callback function that is called everytime matlab throws an error. I know I can try/catch, but I would prefer for this to happen globally whatever script I run without having to write something like try, script, catch err, callback(err), end everytime I want to run something, also I want the callback when I use evaluate selection etc anyway.
2 Commenti
Steven Lord
il 8 Nov 2024 alle 13:37
What are you trying to accomplish with this?
Do you want this to run even if the code catches the error and handles it itself, interposing your callback before the code the author of the function you're trying to run has specifically implemented in a catch block? [No, you don't.]
Risposte (3)
Walter Roberson
il 7 Nov 2024 alle 21:42
Sorry, there is no way of doing this.
The most you can do is put a try/catch around the top level of your code. However, when the catch would be invoked, the call stack would already have been unwound all the way back. There is no way of putting in a general-purpose error callback that would operate at the level of individual errors.
You can set dbstop if error to stop when errors are caught -- but if you do so then you will be returned to the keyboard each time, instead of being able to program a response.
0 Commenti
Steven Lord
il 10 Nov 2024 alle 6:23
Depending on what exactly you want to clean up, creating an onCleanup object may be of use to you. When this object is destroyed (generally at the end of the normal operation of the function in which it is created, assuming it was not returned as an output, or when the function throws an error and so terminates unexpectedly) the function that you provided when it was created gets run.
callFunctionThatWillNotError(); % Cleanup happens at end of normal function operation
callFunctionThatWillError(); % Cleanup happens before function terminates due to error
function x = callFunctionThatWillNotError
cleanupObj = onCleanup(@() disp("Cleaning up now 1"));
x = 0;
for k = 1:5
x = x + k;
fprintf("The value of x is now %d.\n", x)
end
end
function callFunctionThatWillError
cleanupObj = onCleanup(@() disp("Cleaning up now 2"));
x = 0;
for k = 1:5
x = x + ones(k);
fprintf("The value of x is now %s.\n", mat2str(x))
end
end
0 Commenti
Vedere anche
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!