Catching Matlab state variables in the try-catch MException.

5 Ansichten (letzte 30 Tage)
D. Plotnick
D. Plotnick am 28 Jun. 2018
Beantwortet: Guillaume am 28 Jun. 2018
Hello, I have a question about error handling. I have a code that is scanning through files and doing some operations on them, and it will occasionally hit an error. When I hit this error, I would like to save some of the 'state' variables of my code beyond just the location in the call-tree that it happened: this may include the name of the file that the error occurred on, the number of iterations performed before the error, etc. Saving might be in a matfile, or just recorded in a diary, but I want to access that information.
Now, I know I can do this if I use a try-catch statement inside of each region of code that may crash, such that Matlab still has access to the state information when the error is caught. However, I want to create a higher level function of the form
function onError(ME,state)
switch ME.identifier
case 1
record(state)
rethrow(ME)
case 2
record(state)
getReport(ME);
warning('Your code did something naughty')
end
This onError code will be placed at a high level of the code and be specifically designed for handling errors that are not handled locally in the lower level code: if a low-level code has a rethrow(ME) I want it to head up to this big guy. However, I see no way to encode whatever state information I want into the MException class, and that is the only information 'caught' by try-catch.
Ideas?

Akzeptierte Antwort

Guillaume
Guillaume am 28 Jun. 2018
Unfortunately for you, when an exception is thrown by a function and that exception is not caught within the function, all the local variables are destroyed. So once the exception has left the function, there's no way to recover the state of the function.
One way or another to achieve what you want you're going to have to modify all the functions that may crash. Either the functions have to catch the exception, record their state, then rethrow the error or they have to record their state everytime they change so that when the exception is thrown the state is already recorded.

Weitere Antworten (0)

Kategorien

Mehr zu Exception Handling finden Sie in Help Center und File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by