2013-09-03 3 views
2

을 종료하지 않고 나는 다음과 같은 상황을 가지고 :점프는 결국 함수/프로 시저

procedure Test; 
begin 
repeat 
    TryAgain := FALSE; 
    try 
    // Code 
    // Code 
    if this and that then begin 
    TryAgain := TRUE; 
    exit; 
    end; 
    finally 
    // CleanUpCode 
    end; 
until TryAgain = FALSE; 
end; 

내가 exit를 호출하지 않고 마지막으로 섹션으로 이동할 수 있습니다 어떻게 그렇게 자동 또한 repeat 바닥 글을 호출?

+3

['Continue'] (http://docwiki.embarcadero.com/Libraries/XE2/en/System.Continue)를 사용하여 다음 반복을 진행하십시오. – TLama

+0

@TLama 계속해서 마침내 전화하지 않겠습니까? –

+2

'if ... end'가'try' 섹션의 끝에 있으면'exit'를 제거한다고 가정 할 때 정의에 의해'finally'에 넘어 가지 않습니까? 아니면'if ... end'와'finally' 사이에 정말로 다른 코드가 있습니까? – lurker

답변

11

Continue을 사용하여 다음 반복으로 진행하십시오. try..finally 블록의 finally 부분의 코드는 항상 실행되도록 설계, 그래서 당신이 강제 경우에도 다음 반복으로 건너된다

procedure TForm1.Button1Click(Sender: TObject); 
begin 
    repeat 
    TryAgain := False; 
    try 
     if SomeCondition then 
     begin 
     TryAgain := True; 
     // this will proceed the finally block and go back to repeat 
     Continue; 
     end; 
     // code which would be here will execute only if SomeCondition 
     // is False, because calling Continue will skip it 
    finally 
     // code in this block is executed always 
    end; 
    until 
    not TryAgain; 
end; 

그러나 단순히 이런 식으로 쓸 수있는 바로 그 논리 :

procedure TForm1.Button1Click(Sender: TObject); 
begin 
    repeat 
    TryAgain := False; 
    try 
     if SomeCondition then 
     begin 
     TryAgain := True; 
     end 
     else 
     begin 
     // code which would be here will execute only if SomeCondition 
     // is False 
     end; 
    finally 
     // code in this block is executed always 
    end; 
    until 
    not TryAgain; 
end; 
7

마침내 call 일 필요는 없습니다. exit을 제거하기 만하면 모든 루프 반복이 끝날 때 finally에있는 코드를 자동으로 실행할 수 있어야합니다. 여기에 코드가 입증의 다음 finally마다 반복의 끝에서 실행되지 않은 경우

program Project1; 

{$APPTYPE CONSOLE} 

uses 
    SysUtils; 

var 
    i, j, Dummy: Integer; 
    TryAgain: Boolean; 

begin 
    i := 0; 
    Dummy := 0; 
    TryAgain := True; 
    repeat 
    try 
     for j := 0 to 200 do 
     Dummy := Dummy + 1; 
    finally 
     Inc(i); 
    end; 
    TryAgain := (i < 10); 
    until not TryAgain; 
    WriteLn(i); 
    ReadLn; 
end. 

repeat은 끝이 없을 것, ifinally에서 증가하기 때문에, 그리고 종료를 실행하지 않은 경우 조건이 충족되지 않을 것입니다. 대신, 11을 종료하고 출 력합니다. 이는 repeat 루프의 반복마다 finally이 실행 중임을 나타냅니다. (finally이 추가 시간을 실행하기 때문에 10 대신 11을 출력합니다.

관련 문제