Repeat Try/Catch loop?

조회 수: 153 (최근 30일)
Tom
Tom 2013년 7월 22일
편집: Voss 2024년 3월 28일 21:44
I have code that sometimes results in an error, and sometimes not. I'd like to have the code run, and then if an error occurs try again until there is no error. Could this be done using a try/catch loop? I.e. the catch statement would tell the program to repeat the try statements? I'm not sure how to implement this.
Thanks!

채택된 답변

Evan
Evan 2013년 7월 22일
편집: Evan 2013년 7월 22일
You could embed your try/catch statements in a while loop, then check a condition at the beginning each iteration to see if the previous iteration ended in an error.
This could either be done through dealing with the MException object itself or just through setting a counter both inside the catch portion and outside the try/catch statement. When the two counters don't match up, you know that you have just had a successful run.
count = 0;
err_count = 0;
while count == err_count
try
i = randi(9);
if i ~= 7
error
end
catch MyErr
err_count = err_count + 1;
end
count = count + 1;
end
  댓글 수: 3
DGM
DGM 2024년 3월 28일 21:34
편집: DGM 2024년 3월 28일 21:35
Here's an idea, though I don't really know why a while loop couldn't be used.
maxtries = 20;
failcount = 0;
for k = 1:maxtries
try
sometimeserror(0.8);
break;
catch
failcount = failcount + 1;
end
end
function sometimeserror(p)
% p is the probability of error
if rand() < p
error('oh gosh i''m so sorry. my bad.');
end
end
Voss
Voss 2024년 3월 28일 21:38
편집: Voss 2024년 3월 28일 21:44
count = 0;
err_count = 0;
max_n_tries = 10; % max number of tries
success = false;
for jj = 1:max_n_tries
try
i = randi(9);
if i ~= 7
error
end
catch MyErr
err_count = err_count + 1;
end
count = count + 1;
if count ~= err_count
% stop looping as soon as count ~= err_count
success = true;
break
end
end
Or, an alternate while loop:
while true
try
% something that might throw an error
break
end
end

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Daniel Shub
Daniel Shub 2013년 7월 22일
편집: Daniel Shub 2013년 7월 22일
You could do something like
function varargout = myfunc(varargin)
try
thingThatSometimesCrashes;
catch
[vargout{1:nargout}] = myfunc(varargin{:})
end
end
This is a recursive loop. If thingThatSometimesCrashes crashes too many times in a row, the function will exceed the recursion limit and still crash. You could instead do a loop with a flag
function varargout = myfunc(varargin)
myflag = true;
while myflag
try
thingThatSometimesCrashes;
myflag = false;
end
end
end

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by