How do I throw an error from TimerFcn?
6 views (last 30 days)
Show older comments
Hi,
I am trying to time out a MATLAB function that may or may not take too long to execute. I am able to use timers to throw errors, but they do not appear to be in a form that can be caught within a try-catch block. As an example, the code that I am using is:
function tmptimer(time_out)
t = timer('TimerFcn', 'error(''timeout'')', 'StartDelay', time_out);
start(t);
try
input('Waiting to timeout'); % Example. Can be an arbitrary function
catch
fprintf('Caught the error');
delete(t);
end
end
The output by running something like
>> tmptimer(1)
is:
Waiting to timeout??? Error while evaluating TimerFcn for timer 'timer-49'
timeout
However, the error does not stop execution! In other words, the command window still keeps waiting for the input in this particular case. Only when I do a Ctrl+C, do I get:
??? Operation terminated by user during ==> tmptimer at 7
Can anyone tell me how I can generate an error that can be picked up by a try-catch block or if there is any other way at all to time out an arbitrary function call?
Thanks
1 Comment
Jim Petersen
on 21 Nov 2020
I have exactly the same problem. Can someone please answer this question?
Answers (1)
Steven Lord
on 21 Nov 2020
The TimerFcn is running at the same time as MATLAB is executing the try / catch block but it's not executing "inside" the try / catch so what you're trying to do won't work.
You could have the TimerFcn set some variable or property that the code inside the try / catch block polls periodically (maybe storing it in the UserData property of the timer itself), or you could have it notify an event associated with some object that your code has added a listener to detect, or if the TimerFcn was nested inside the function where the try / catch block is written it could update a workspace variable in the shared nested workspace. There are other options, but those are the first that come to mind.
1 Comment
Jim Petersen
on 21 Nov 2020
Thanks a lot Steven for the speedy response.
I'm waiting for a certain number of terminators to occur in the serial data stream. If something goes wrong, and the required number of terminators is never reached, then I want to recover. There is other event-driven code executing that I don't want to block, so I'm using the waitfor. I'm trying to do something like the following:
try
obj.tmrObj.start(txd);
waitfor(obj, 'isTerminatorEvent', true);
obj.tmrObj.stop();
catch ME
obj.timeOutMsg(1);
rethrow(ME);
end
See Also
Categories
Find more on Startup and Shutdown in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!