How do I throw an error from TimerFcn?
조회 수: 6 (최근 30일)
이전 댓글 표시
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
Jim Petersen
2020년 11월 21일
I have exactly the same problem. Can someone please answer this question?
답변 (1개)
Steven Lord
2020년 11월 21일
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
Jim Petersen
2020년 11월 21일
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
참고 항목
카테고리
Help Center 및 File Exchange에서 Startup and Shutdown에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!