MATLAB Answers

Catching Matlab state variables in the try-catch MException.

조회 수: 6(최근 30일)
D. Plotnick
D. Plotnick 2018년 6월 28일
답변: Guillaume 2018년 6월 28일
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
case 2
warning('Your code did something naughty')
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.

채택된 답변

Guillaume 2018년 6월 28일
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.

추가 답변(0개)

Community Treasure Hunt

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

Start Hunting!

Translated by