Flow-control structures: Difference between revisions

m
→‎{{header|Ada}}: added 'return'
m (→‎{{header|Ada}}: added 'return')
 
(183 intermediate revisions by 53 users not shown)
Line 1:
{{Task|Control Structures}}
{{Control Structures}}
[[Category:Flow control]]
In this task, we document common flow-control structures. One common example of a flow-control structure is the <tt>goto</tt> construct. Note that [[Conditional Structures]] and [[Iteration|Loop Structures]] have their own articles/categories.
 
;Task:
Document common flow-control structures.
 
 
One common example of a flow-control structure is the &nbsp; <big><code> goto </code></big> &nbsp; construct.
 
Note that &nbsp; [[Conditional Structures]] &nbsp; and &nbsp; [[Iteration|Loop Structures]] &nbsp; have their own articles/categories.
 
 
;Related tasks:
* &nbsp; [[Conditional Structures]]
* &nbsp; [[Iteration|Loop Structures]]
<br><br>
 
=={{header|11l}}==
{{trans|Python}}
===Loops===
11l supports ''L.break'' and ''L.continue'' to exit from a loop early or short circuit the rest of a loop's body and "continue" on to the next loop iteration.
<syntaxhighlight lang="11l">V n = 10
Int result
 
L(i) 0 .< n
I (n % 2) == 0
L.continue
I (n % i) == 0
result = i
L.break
L.was_no_break
result = -1
print(‘No odd factors found’)</syntaxhighlight>
In addition, as shown in the foregoing example, 11l loops support an ''L.was_no_break'' suite which can be used to handle cases when the loop was intended to search for something, where the code would break out of the loop upon finding its target.
 
=={{header|360 Assembly}}==
Common 360 opcodes for flow-control structures:
===Unconditional Branch (B)===
To perform a 'goto'.
<syntaxhighlight lang="360asm">
B TESTPX goto label TESTPX
BR 14 goto to the address found in register 14
</syntaxhighlight>
===Branch and Link (BAL)===
To perform a 'call' to a subroutine. The first register at execution time is the next sequential address to allow a 'return'.
<syntaxhighlight lang="360asm">
LA 15,SINUSX load in reg15 address of function SINUSX
BALR 14,15 call the subroutine SINUX and place address RETPNT in reg14
RETPNT EQU *
SINUSX EQU * subroutine SINUSX
...
BR 14 return to caller
</syntaxhighlight>
 
===Conditional Branch (BC)===
Fistly a compare instruction set the condition code (cc), secondly a conditional branch is performed.
<syntaxhighlight lang="360asm">
L 4,A Load A in register 4
C 4,B Compare A with B
BH TESTGT Branch on High if A>B then goto TESTGT
BL TESTLT Branch on Low if A<B then goto TESTLT
BE TESTEQ Branch on Equal if A=B then goto TESTEQ
BNH TESTLE Branch on Not High if A<=B then goto TESTLE
BNL TESTGE Branch on Not Low if A>=B then goto TESTGE
BNE TESTNE Branch on Not Equal if A<>B then goto TESTNE
</syntaxhighlight>
===Branch on Count (BCT)===
To perform unconditional loops.
<syntaxhighlight lang="360asm">
LA 3,8 r3 loop counter
LOOP EQU *
... loop 8 times (r3=8,7,...,2,1)
BCT 3,LOOP r3=r3-1 ; if r3<>0 then loop
</syntaxhighlight>
===Branch on Index (BX.)===
BXLE to perform loops in old Fortran style with 3 registers.
<syntaxhighlight lang="360asm">
* do i=1 to 8 by 2
L 3,1 r3 index and start value 1
LA 4,2 r4 step 2
L 5,8 r5 to value 8
LOOPI EQU *
... loop 4 times (r3=1,3,5,7)
BXLE 3,4,LOOPI r3=r3+r4; if r3<=r5 then loop
</syntaxhighlight>
BXH to perform backward loops with 3 registers.
<syntaxhighlight lang="360asm">
* do i=8 to 1 by -2
L 3,1 r3 index and start value 8
LH 4,=H'-2' r4 step -2
L 5,8 r5 to value 1
LOOPI EQU *
... loop 4 times (r3=8,6,4,2)
BXH 3,4,LOOPI r3=r3+r4; if r3>r5 then loop
</syntaxhighlight>
 
=={{header|6502 Assembly}}==
Line 7 ⟶ 101:
===JMP===
The jump instruction immediately jumps to any address:
<langsyntaxhighlight lang="6502asm"> JMP $8000 ;immediately JuMP to $8000 and begin executing
;instructions there.</langsyntaxhighlight>
The indirect jump instruction immediately jumps to the address contained in the address:
<langsyntaxhighlight lang="6502asm"> JMP ($8000) ;immediately JuMP to the address in memory locations
;$8000 and $8001</langsyntaxhighlight>
 
===JSR===
The jump to subroutine instruction pushes the address of the next instruction minus one onto the stack and jumps to any address:
<langsyntaxhighlight lang="6502asm"> JSR $8000 ;Jump to SubRoutine</langsyntaxhighlight>
A return from subroutine instruction pops the return address off the stack, adds one, and jumps to that location:
<langsyntaxhighlight lang="6502asm"> RTS ;ReTurn from Subroutine</langsyntaxhighlight>
 
===NMI===
This isn't a CPU instruction, it stands for Non-Maskable Interrupt. A non-maskable interrupt will push the program counter and the flags (in that order) then execute <code>JMP ($FFFA)</code>, thereby reading the address stored there and jumping to that address. This interrupt cannot be disabled with <code>SEI</code>. The code at that address will need to end in <code>RTI</code> to properly return from the interrupt.
 
===BRK===
Similar to NMI, except the CPU executes execute <code>JMP ($FFFE)</code> instead. This is intended for debugging but is not of much practical use. Returning from this interrupt will skip the instruction after the <code>BRK</code>.
A break instruction causes a non-maskable interrupt (setting the interrupt flag), pushes the current program counter address plus one onto the stack, pushes the flags onto the stack, then jumps to the address in the break vector (commonly at $FFFE and $FFFF):
 
<lang 6502asm> BRK ;BReaK</lang>
===IRQ===
The return from interrupt instruction pops the flags off the stack, pops the return address off the stack, adds one, and jumps to that location:
This is a generic interrupt that jumps to the handler stored in memory location <code>$FFFE</code>, but unlike <code>BRK</code> it doesn't skip anything when it returns. This can be disabled with <code>SEI</code>, and often can be configured at runtime to occur upon specific events, unlike NMI which usually is triggered by the same event. Use <code>RTI</code> to return from this interrupt.
<lang 6502asm> RTI ;ReTurn from Interrupt</lang>
 
=={{header|68000 Assembly}}==
<code>JMP</code>,<code>JSR</code>,<code>RTS</code>, and branching work almost identical to [[6502 Assembly]]. There are a few exceptions:
* Compared to the 6502, <code>BCS</code> and <code>BCC</code> are the opposite for the purposes of unsigned comparisons. (The 6502 is actually the odd one out here - on most architectures "carry clear" represents greater than or equal, but 6502 is the opposite!)
* An additional <code>BSR</code> can be used for nearby subroutines. This is quicker than a <code>JSR</code> but has a limited range. It is also <i>not</i> relocatable, in the sense that if you copy a routine to RAM that uses this instruction and try to execute it there, unless you also copied the routine that you're <code>BSR</code>ing to, you're in for a nasty surprise. Many assemblers will auto-convert JSR to BSR and there's no easy way to conditionally stop that from happening except by inlining bytecode.
* <code>DBRA</code> is used for looping. A register operand is decremented with each loop. The loop terminates when the value in the register underflows from <tt>0</tt> to <tt>0xFFFF</tt>. As a result, the number of times you want to loop must be reduced by one. <code>DBRA</code> stands for "decrement, branch always" and there are other condition codes you can use, that will decrement the register operand (at word length) and branch <i>unless</i> the condition is met.
* <code>TRAP #</code> is often used by the firmware to perform built-in tasks such as reading a keyboard or mouse input. Some systems (such as the Sega Genesis and NEO GEO) allow the programmer to alter the destination of the traps, allowing for custom error handlers. (However, these locations are usually in ROM and thus cannot be changed at runtime.)
 
=={{header|Ada}}==
 
===goto===
<langsyntaxhighlight lang="ada"><<Top>>
Put_Line("Hello, World");
goto Top;</langsyntaxhighlight>
 
===exit===
Exit is used to break out of loops. Exit can be used with a label to break out of an inner loop to an outer loop and its enclosing outer loop:
<langsyntaxhighlight lang="ada">Outer:
loop
-- do something
loop
--if doFinished somethingthen
loop
-- do something else
exit Outer; -- exits both the inner and outer loops
end loopif;
-- do something else
end loop;</lang>
end loop;
end loop Outer;</syntaxhighlight>
or, more idiomatically,
<syntaxhighlight lang="ada">Outer:
loop
-- do something
loop
exit Outer when Finished;
-- do something else
end loop;
end loop Outer;</syntaxhighlight>
 
===return===
A procedure can be exited early, if there’s no more to be done.
<syntaxhighlight lang="ada">procedure Foo is
begin
-- do something
if Nothing_More_To_Do then
return;
end if;
-- do more
end Foo;</syntaxhighlight>
 
===asynchronous transfer of control===
A sequence of operation can be aborted with an asynchronous transfer of control to an alternative:
<langsyntaxhighlight lang="ada">select
delay 10.0;
Put_Line ("Cannot finish this in 10s");
Line 49 ⟶ 177:
-- do some lengthy calculation
...
end select;</langsyntaxhighlight>
The alternative can be a delay statement or else an entry point call followed by a sequence of operations. The statement blocks at the delay or entry call and executes the sequence of the operation introduced by '''then abort'''. If blocking is lifted before completion of the sequence, the sequence is aborted and the control is transferred there.
 
Line 60 ⟶ 188:
See also [[Exceptions#ALGOL_68|Exceptions]] to see how '''ALGOL 68''' handles ''transput'' events.
===One common use of a label in '''ALGOL 68''' is to break out of nested loops.===
<langsyntaxhighlight lang="algol68">(
FOR j TO 1000 DO
FOR i TO j-1 DO
Line 71 ⟶ 199:
OD;
done: EMPTY
);</langsyntaxhighlight>
===Multi way jump using labels and '''EXIT''' to return result ===
<langsyntaxhighlight lang="algol68">STRING medal = (
[]PROC VOID award = (gold,silver,bronze);
 
Line 84 ⟶ 212:
);
 
print(("Medal awarded: ",medal, new line));</langsyntaxhighlight>
===Another use is to implement finite state machines ===
<langsyntaxhighlight lang="algol68">STRING final state = (
INT condition;
PROC do something = VOID: condition := 1 + ENTIER (3 * random);
Line 106 ⟶ 234:
"State N"
);
print(("Final state: ",final state, new line));</langsyntaxhighlight>
===ALGOL 68G implements a Refinement Preprocessor to aid with top down code development ===
<langsyntaxhighlight lang="algol68"># example from: http://www.xs4all.nl/~jmvdveer/algol.html - GPL #
determine first generation;
WHILE can represent next generation
Line 129 ⟶ 257:
printf (($lz","3z","3z","2z-d$, current,
$xz","3z","3z","2z-d$, previous,
$xd.n(real width - 1)d$, current / previous)).</langsyntaxhighlight>
{{out}}
Sample output:
<pre>
Exited when: i=13, j=53
Line 141 ⟶ 269:
etc...
</pre>
 
=={{header|ALGOL W}}==
As well as structured flow-control structures (loops, if-then-else, etc.) Algol W has a goto statement. A goto can lead out of the current procedure, which can be used for error handling. Goto can be written as "goto" or "go to".
<syntaxhighlight lang="algolw">begin
integer i;
integer procedure getNumber ;
begin
integer n;
write( "n> " );
read( i );
if i< 0 then goto negativeNumber;
i
end getNumber ;
 
i := getNumber;
write( "positive or zero" );
go to endProgram;
negativeNumber:
writeon( "negative" );
endProgram:
end.</syntaxhighlight>
 
=={{header|ARM Assembly}}==
<syntaxhighlight lang="arm assembly">SWI n ;software system call
B label ;Branch. Just "B" is a branch always, but any condition code can be added for a conditional branch.
;In fact, almost any instruction can be made conditional to avoid branching.
 
BL label ;Branch and Link. This is the equivalent of the CALL command on the x86 or Z80.
;The program counter is copied to the link register, then the operand of this command becomes the new program counter.
 
BX Rn ;Branch and Exchange. The operand is a register. The program counter is swapped with the register specified.
;BX LR is commonly used to return from a subroutine.
 
addeq R0,R0,#1 ;almost any instruction can be made conditional. If the flag state doesn't match the condition code, the instruction
;has no effect on registers or memory.</syntaxhighlight>
 
=={{header|Arturo}}==
=== return ===
return from the function currently being execute
=== loop control ===
Arturo's loop control statements are: <code>break</code> and <code>continue</code>
=== exceptions ===
Normally, in Arturo we'd use either <code>try [...]</code> or <code>try? [...] else [...]</code> blocks.
 
=={{header|AutoHotkey}}==
<langsyntaxhighlight AutoHotkeylang="autohotkey">MsgBox, calling Label1
Gosub, Label1
MsgBox, Label1 subroutine finished
Line 156 ⟶ 327:
Label2:
MsgBox, Label2 will not return to calling routine
Return</langsyntaxhighlight>
 
=={{header|AWK}}==
 
Awk has ''break'' and ''continue'' for loop control, as in C.
The [awk] programming language is data driven. However, Awk has ''break'' and ''continue'' for loop control, as in C.
<lang awk>$ awk 'BEGIN{for(i=1;;i++){if(i%2)continue; if(i>=10)break; print i}}'
 
<syntaxhighlight lang="awk">$ awk 'BEGIN{for(i=1;;i++){if(i%2)continue; if(i>=10)break; print i}}'
2
4
6
8</langsyntaxhighlight>
 
 
=={{header|BASIC256}}==
<syntaxhighlight lang="basic256">
gosub subrutina
 
bucle:
print "Bucle infinito"
goto bucle
 
 
subrutina:
print "En subrutina"
pause 10
return
end
</syntaxhighlight>
 
 
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
BBC BASIC has '''GOSUB''' and '''GOTO''' but they are deprecated.
<syntaxhighlight lang="bbcbasic"> GOSUB subroutine
(loop)
PRINT "Infinite loop"
GOTO loop
END
(subroutine)
PRINT "In subroutine"
WAIT 100
RETURN</syntaxhighlight>
 
=={{header|Bracmat}}==
In Bracmat, the thing that comes closest to a GOTO construct is evaluation of a variable that contains some code, ending with an evaluation of the same variable. Due to tail recursion optimization this can run forever. Example:
<syntaxhighlight lang="bracmat"> ( LOOP
= out$"Hi again!"
& !LOOP
)
& out$Hi!
& !LOOP</syntaxhighlight>
{{out}}
<pre>Hi!
Hi again!
Hi again!
Hi again!
...
</pre>
 
=={{header|C}}==
===goto===
One common use of goto in C is to break out of nested loops.
<langsyntaxhighlight lang="c">int main()
{
int i,j;
Line 181 ⟶ 403:
out:
return 0;
}</langsyntaxhighlight>
 
=={{header|C sharp|C#}}==
===return===
terminates the function and returns control to the caller.
<syntaxhighlight lang="csharp">int GetNumber() {
return 5;
}</syntaxhighlight>
===throw===
throws (or rethrows) an exception. Control is transferred to the nearest catch block capable of catching the exception.<br/>
A <code>finally</code> block is always executed before control leaves the <code>try</code> block.
<syntaxhighlight lang="csharp">try {
if (someCondition) {
throw new Exception();
}
} catch (Exception ex) {
LogException(ex);
throw;
} finally {
cleanUp();
}</syntaxhighlight>
===yield return and yield break===
In a generator method, <code>yield return</code> causes the method to return elements one at a time. To make this work, the compiler creates a state machine behind the scenes. <code>yield break</code> terminates the iteration.
<syntaxhighlight lang="csharp">public static void Main() {
foreach (int n in Numbers(i => i >= 2) {
Console.WriteLine("Got " + n);
}
}
 
IEnumerable<int> Numbers(Func<int, bool> predicate) {
for (int i = 0; ; i++) {
if (predicate(i)) yield break;
Console.WriteLine("Yielding " + i);
yield return i;
}
}
</syntaxhighlight>
{{out}}
<pre>
Yielding 0
Got 0
Yielding 1
Got 1</pre>
===await===
is used to wait for an asynchronous operation (usually a Task) to complete. If the operation is already completed when <code>await</code> is encountered, the method will simply continue to execute. If the operation is not completed yet, the method will be suspended. A continuation will be set up to execute the rest of the method at a later time. Then, control will be returned to the caller.
<syntaxhighlight lang="csharp">async Task DoStuffAsync() {
DoSomething();
await someOtherTask;//returns control to caller if someOtherTask is not yet finished.
DoSomethingElse();
}
</syntaxhighlight>
===break and continue===
<code>continue</code> causes the closest enclosing loop to skip the current iteration and start the next iteration immediately.<br/>
<code>break</code> terminates the closest enclosing loop or <code>switch</code> statement. Control is passed to the statement that follows the terminated statement.
===<code>goto</code>===
<code>goto Label;</code> will cause control to jump to the statement with the corresponding label. This can be a <code>case</code> label inside a <code>switch</code>.<br/>
Because the label must be in scope, <code>goto</code> cannot jump inside of a loop.
<syntaxhighlight lang="csharp">while (conditionA) {
for (int i = 0; i < 10; i++) {
if (conditionB) goto NextSection;
DoSomething(i);
}
}
NextSection: DoOtherStuff();</syntaxhighlight>
 
=={{header|C++}}==
=== goto ===
{{works with|GCC|3.3.4}}
<langsyntaxhighlight lang="cpp">#include <iostream>
 
int main()
Line 193 ⟶ 478:
std::cout << "Hello, World!\n";
goto LOOP;
}</langsyntaxhighlight>
 
Note that "goto" may also be used in conjunction with other forms of branching.
Line 201 ⟶ 486:
 
Exceptions are a way to give control back to a direct or indirect caller in case of an error. Note that throwing exceptions is usually very expensive, therefore they generally should only be used for exceptional situations.
<langsyntaxhighlight lang="cpp">#include <iostream>
#include <ostream>
 
Line 271 ⟶ 556:
<< "inside foobar(). Thus this catch-all block never gets invoked.\n";
}
}</langsyntaxhighlight>
 
=={{header|COBOL}}==
=== CALL ===
This transfers control to a subprogram, with control eventually being returned (provided the subprogram does not terminate the program).
 
=== CHAIN ===
This transfers control to the subprogram specified with ''no'' return of control. <code>CHAIN</code> is a non-standard extension
created by Micro Focus and is found in [[Visual COBOL]].
 
=== EXIT ===
<code>EXIT</code> takes a variety of clauses:
* <code>PARAGRAPH</code>/<code>PERFORM</code>/<code>SECTION</code>: Control will be transferred immediately past the end of those blocks.
* <code>PERFORM CYCLE</code>: The current iteration of the <code>PERFORM</code> will stop, and control will go to the clauses of the <code>PERFORM</code> which will determine if another iteration is to run.
* <code>PROGRAM</code>: If used in a called function, execution of it is stopped and control returned to the calling program. If it is used in the main program, the statement is non-functional and ignored.
The <code>PERFORM</code>/<code>PERFORM CYCLE</code> clauses can only be used inside of an inline <code>PERFORM</code> statement.
 
=== GOBACK ===
If used in a called function, control will transferred back to the calling program. If it is used in the main program, the program will be terminated.
 
=== GO TO ===
Basic use:
<syntaxhighlight lang="cobol"> PROGRAM-ID. Go-To-Example.
 
PROCEDURE DIVISION.
Foo.
DISPLAY "Just a reminder: GO TOs are evil."
 
GO TO Foo
.</syntaxhighlight>
 
A <code>GO TO</code> can take a <code>DEPENDING ON</code> clause which will cause program flow to go to a certain paragraph/section depending on a certain value.
<syntaxhighlight lang="cobol"> GO TO First-Thing Second-Thing Third-Thing
DEPENDING ON Thing-To-Do
 
* *> Handle invalid thing...</syntaxhighlight>
The previous example is equivalent to:
<syntaxhighlight lang="cobol"> EVALUATE Thing-To-Do
WHEN 1
* *> Do first thing...
 
WHEN 2
* *> Do second thing...
 
WHEN 3
* *> Do third thing...
 
WHEN OTHER
* *> Handle invalid thing...
END-EVALUATE</syntaxhighlight>
 
=== ALTER ===
The much maligned altered GO.
 
''The ALTER statement is now obsolete and not even mentioned in the COBOL 2014 standard.''
 
If anyone wonders why this was ever designed into a language, you have to look back to the days of 8K RAM, multi-million dollar computers, and source code that was entered on punch cards, one line per card. Think of physically recoding an entire deck of punch cards (say even 6,000 lines worth) versus ALTERing a few paragraphs, that jump to new code at the end of the deck, and you may see one small reason why this was ever built into early versions of COBOL. Then ponder what the state of the code would be after three or four (or fifty) such patches, and then see why ALTER was deemed obsolete shortly after terminals and disk become the common way of entering programs.
 
Then pause to think about the fact that some COBOL code, written before ALTER went out of fashion, is still in production, to understand why it was implemented in GnuCOBOL, a relatively new COBOL dialect, still in development as of 2016 (along with other modern COBOL implementations, that support COBOL 2014, and yet continue to support language constructs that date all the way back to COBOL-60).
 
{{works with|GnuCOBOL}}
<syntaxhighlight lang="cobol">
identification division.
program-id. altering.
 
procedure division.
main section.
 
*> And now for some altering.
contrived.
ALTER story TO PROCEED TO beginning
GO TO story
.
 
*> Jump to a part of the story
story.
GO.
.
 
*> the first part
beginning.
ALTER story TO PROCEED to middle
DISPLAY "This is the start of a changing story"
GO TO story
.
 
*> the middle bit
middle.
ALTER story TO PROCEED to ending
DISPLAY "The story progresses"
GO TO story
.
 
*> the climatic finish
ending.
DISPLAY "The story ends, happily ever after"
.
 
*> fall through to the exit
exit program.
</syntaxhighlight>
{{out}}
<pre>
prompt$ cobc -xj altering.cob
This is the start of a changing story
The story progresses
The story ends, happily ever after
</pre>
 
=== INVOKE ===
The <code>INVOKE</code> statement is used to transfer control to a method of a class/factory object.
 
=== PERFORM ===
The <code>PERFORM</code> statement can be used to transfer program flow to the specified sections/paragraphs in the subprogram, with control being returned when the end of the last paragraph/section or a relevant <code>EXIT</code> statement is reached.
<syntaxhighlight lang="cobol"> PROGRAM-ID. Perform-Example.
 
PROCEDURE DIVISION.
Main.
PERFORM Moo
PERFORM Display-Stuff
PERFORM Boo THRU Moo
 
GOBACK
.
 
Display-Stuff SECTION.
Foo.
DISPLAY "Foo " WITH NO ADVANCING
.
 
Boo.
DISPLAY "Boo " WITH NO ADVANCING
.
 
Moo.
DISPLAY "Moo"
.</syntaxhighlight>
{{out}}
<pre>
Moo
Foo Boo Moo
Boo Moo
</pre>
 
=== STOP RUN ===
This immediately terminates the program.
 
=={{header|Comal}}==
===Call a procedure===
<syntaxhighlight lang="comal">myprocedure
END // End of main program
PROC myprocedure
PRINT "Hello, this is a procedure"
ENDPROC myprocedure</syntaxhighlight>
 
===Exit a loop===
<syntaxhighlight lang="comal">LOOP
PRINT "I'm in a loop!"
EXIT
ENDLOOP
PRINT "But i somehow got out of it."</syntaxhighlight>
 
===Conditional exit===
<syntaxhighlight lang="comal">PRINT "I'm in a loop!"
LOOP
INPUT "Do you want to exit?":answer$
EXIT WHEN answer$="y"
ENDLOOP
PRINT "You got out of it."</syntaxhighlight>
 
===Goto===
<syntaxhighlight lang="comal">PRINT "Hello world"
GOTO label
PRINT "This line will never be output"
label:
PRINT "This program will end thanks to the evil GOTO statement"
END</syntaxhighlight>
 
=={{header|D}}==
=== goto ===
<syntaxhighlight lang="d">import std.stdio;
<lang d>label1:
 
writeln ("i'm in your infinite loop");
void main() {
goto label1;</lang>
label1:
writeln("I'm in your infinite loop.");
goto label1;
}</syntaxhighlight>
 
=== Exceptions ===
D supports standardthe try/catch/finally mechanismsmechanism:
<syntaxhighlight lang="d">import std.stdio;
<lang d>void main (char[][] args)
 
{
class DerivedException : Exception {
try
this(string msg) { super(msg); }
{
}
if (args[1] == "throw") throw new Exception ("message");
 
}
void main(string[] args) {
catch (DerivedException ex)
try {
{
if (args[1] == "throw")
// we never threw a DerivedException, so this block is never called
throw new Exception("message");
writefln ("caught derived exception %s", ex.toString);
} catch (DerivedException ex) {
}
// We never threw a DerivedException, so this
catch (Exception ex)
// block is never called.
{
writefln writefln("caught derived exception: %s", ex.toString);
} catch (Exception ex) {
}
writefln("caught exception: %s", ex);
catch (Object ex)
} catch (Throwable ex) {
{
writefln("caught throwable: %s", ex);
// Throwing Objects is allowed but discouraged.
} finally {
writefln ("caught object: %s", ex.toString);
writeln("finished (exception or none).");
}
}
finally
}</syntaxhighlight>
{
writeln ("finished (exception or none)");
}
}</lang>
 
=== Scope guards ===
Line 313 ⟶ 775:
 
For instance:
<syntaxhighlight lang="d">import std.stdio;
<lang d>void main (char[][] args)
 
{
void main(string[] args) {
scope (exit) writeln ("gone");
scope(exit)
if (args[1] == "throw") throw new Exception ("message");
writeln("Gone");
scope (exit) writeln ("gone, but we passed the first chance to throw an exception");
 
}</lang>
if (args[1] == "throw")
throw new Exception("message");
 
scope(exit)
writeln("Gone, but we passed the first" ~
" chance to throw an exception.");
}</syntaxhighlight>
 
If the exception is thrown, then the only text that is written to the screen is "gone". If no exception is thrown, both calls to writeln occur.
 
scope (failure) and scope (success) work similarly.
 
=={{header|E}}==
Line 341 ⟶ 810:
 
[[Category:E examples needing attention]] <!-- Needs runnable examples, description of escape-catch, and maybe links to other flow control pages -->
 
=={{header|EasyLang}}==
 
With '''break <n>''' you can break out of a nested loop
 
<syntaxhighlight>
sum = 80036
for i = 0 to 50
for j = 0 to 50
if i * i + j * j * j = sum
print i & "² + " & j & "³ = " & sum
break 2
.
.
.
</syntaxhighlight>
{{out}}
<pre>
23² + 43³ = 80036
</pre>
 
=={{header|Erlang}}==
The one Erlang flow control structure, apart from the ones excluded in the task description, is [[Exceptions]]
 
=={{header|Forth}}==
===CATCH-THROW===
Some Forth implementations have goto, but not the standard. It does have an exception mechanism.
<langsyntaxhighlight lang="forth">: checked-array
CREATE ( size -- ) DUP , CELLS ALLOT
DOES> ( i -- a+i )
Line 357 ⟶ 849:
 
: safe-access ( i -- a[i] )
['] myarray CATCH 1 = IF ." Out of bounds!" 0 THEN ;</langsyntaxhighlight>
 
=={{header|Fortran}}==
===The basic: GO TO ''label''===
Fortran offers <code>GO TO ''label''</code> where ''label'' is a number, an integer, which is prefixed to some executable statement according to the rules of Fortran source layout. It is not considered to be a numerical value, though zero is not an allowed label and leading zero digits are ignored. Fortran has no reserved words and gives no significance to spaces, so that <code>G O TO 12 3 4</code> is just as valid as <code>GO TO 1234</code> and other usages. Text labels are not allowed, however a statement such as <code>GO TO START</code> is possible. Even so, "START" is not itself a label, but the name of a variable which is used in special ways - see the ASSIGN statement usage, below.
 
===Elaborations on GO TO===
A compiler may offer the "assigned GO TO" facility, with statements such as <code>ASSIGN 120 TO THENCE</code> scattered about: 120 is a statement label, not an integer, and any statement label may be assigned to variable THENCE (which is an integer variable) as execution proceeds. A relatively restrained usage would be to select the label of a suitable FORMAT statement to use in a READ or WRITE statement in place of a fixed label, without affecting the flow of control. But <code>GO TO THENCE</code> will cause a GO TO for the current address held in THENCE... Should you yield to temptations such as <code>THENCE = THENCE - 6</code> (treating it as an ordinary integer), a subsequent <code>GO TO THENCE</code> may end execution with an error message, or something else...
 
Aside from facilitating the production of spaghetti code, this sort of behaviour actually can be put to a positive use to handle the situation where in a large programme there may be portions that could be employed from a number of locations, and one does not wish to repeat that code each time - apart from the tedium of punching additional cards, each replication would demand its own unique set of statement labels. Further, such replication increases the total code size and memory is limited... <syntaxhighlight lang="fortran"> ...
ASSIGN 1101 to WHENCE !Remember my return point.
GO TO 1000 !Dive into a "subroutine"
1101 CONTINUE !Resume.
...
ASSIGN 1102 to WHENCE !Prepare for another invocation.
GO TO 1000 !Like GOSUB in BASIC.
1102 CONTINUE !Carry on.
...
Common code, far away.
1000 do something !This has all the context available.
GO TO WHENCE !Return whence I came.</syntaxhighlight>
Since Algol in the 1960s it has been possible to define a routine within a larger routine that has access to all the context of the larger routine and so can be a convenient service routine for it, but Fortran does not allow a subroutine (or function) to be defined within a larger subroutine, except for the arithmetic statement function. One must write separate subroutines and struggle over providing access to context via COMMON and parameters. However, F90 introduced the MODULE arrangement whereby a collection of variables may all be referenced by a group of subroutines in the module without each having COMMON statements in common. Further, it allows a subroutine (or function) to use the CONTAINS feature, after which such a contained routine may be placed. Alas, it may not itself invoke CONTAINS even though Algol allows nesting as desired. And oddly, the contained routine must be at the ''end'' of the containing routine. So much for definition before usage. With such a facility, the possibility arises of perpetrating a GO TO from a contained routine to somewhere in its parent, however the F90 compilers are required to disallow access to outside labels, even those of FORMAT statements - rather a pity for that. Such escapes would have to copy whatever de-allocation steps were needed for a normal exit, which is simple enough on a stack-oriented design such as the B6700. However, its Algol compiler rejected attempts to jump from one routine ''into'' another (!) with the message "Bad GOTO. Too bad." Assembler programmers can do what they want, but for once, Fortran's designers show some restraint.
 
Once started on this path, many opportunities beckon: perhaps not just action "A" (achieved by "subroutine" 1000) is of use, there may be an action "B", and so on. One can then prepare the equivalent of a "to-do" list via something like<syntaxhighlight lang="fortran"> ASSIGN 2000 TO WHENCE !Deviant "return" from 1000 to invoke 2000.
ASSIGN 1103 TO THENCE !Desired return from 2000.
GO TO 1000
1103 CONTINUE</syntaxhighlight>
So that "subroutine" 1000 would be invoked, which then invokes subroutine 2000, which returns via THENCE. And, instead of using simple variables such as THENCE and WHENCE, one could use an array and treat it like a stack... Those familiar with LISP or FORTH and similar languages will recognise a struggle to create new "verbs" from existing verbs, and their resulting usage in compound expressions. This is Philip Greenspun's "tenth" rule of programming.
 
Another such usage would be to implement "coroutines", the classic example being to imagine a system that processes both Fortran statements and Fortran commentary, but each in their own way. After scanning some Fortran source, commentary is found so control flows to resume the commentary processing from where it had left off, then when further Fortran source is found, control flows back whence the Fortran source process left off. This is quite different from having subroutines FCODE and FCOMM which when invoked start at their start each time (as say when a new statement begins) rather than picking up where they left off because the switches occurred in the middle of a statement. Quite aside from questions of mutual recursion.
 
====If one is good, more are better?====
There is also a "computed GO TO" with syntax like <code>GO TO (101,50,75,50), ''n''</code> where ''n'' is an integer variable (or expression) that selects from the list of statement labels: in this example if its value is three, then the third label, 75, will be selected. If the value is less than one or greater than the number of labels in the list, odd behaviour is likely, differing by compiler. Possibly by continuing with the next statement, or ending execution with an error message, or making a leap into the void. This statement can be used to produce a tangle as described for the ASSIGN facility, but is commonly used as a central direction station, or "dispatch table" for instance when a programme accepts an input which is one of a number of commands and after identifying it from a list of recognised commands (such as "List", "Dump", LineFit", "Quit", ''etc.''), performs a computed GO TO to reach the portion that processes that command. Again, familiar to LISP programmers.
 
===Escape from mishap===
An implicit GO TO can appear in READ and WRITE statements (and a few others), that will be taken should there be certain difficulties. Thus <code>READ (IN,6,END = 200, ERR = 300) STUFF</code> reads input from I/O unit IN (an integer value) into variable STUFF according to the FORMAT statement labelled 6. But should there be instead an end-of-file, rather than ending execution with an error code, execution will GO TO label 200, while if there should arise some difficulty with the format of the incoming data (two decimal points in one data field, ''etc.'') then execution will GO TO label 300. FORMAT statements, though labelled, are not considered suitable destinations for GO TO jumps.
 
===Deviant RETURN===
Similar possibilities arise with alternate returns from subroutines and functions, for instance to handle error conditions it might wish to report as with the READ statement. Thus, <code>CALL FRED(THIS,*123,*THENCE)</code> invokes a subroutine FRED with three parameters: THIS, then two oddities. The leading * (or &) signifies that these are no ordinary integers (or expressions) but instead are the labels of statements somewhere within the calling routine. Subroutine FRED might return in the normal way so that execution continues with the following statement, or, it may instead return with a GO TO for one of the labels...<syntaxhighlight lang="fortran"> SUBROUTINE FRED(X,*,*) !With placeholders for unusual parameters.
...
RETURN !Normal return from FRED.
...
RETURN 2 !Return to the second label.
END</syntaxhighlight>
More delicate souls prefer to see an integer parameter whose value will be set by FRED according to the desired condition, and every call to FRED would be followed by a computed GO TO on that value. Except that this statement is also disapproved of, so one is encouraged to code IF, or CASE, ''etc.'' and enjoy the repetition.
 
Thus, a subroutine (or a function) may exit via a RETURN statement, rather than by completing its logic and "falling out" of the end of its definition. If the subprogram is large, these escape holes may be missed by the (human) reader!
 
Persons writing in assembler have further opportunities, for example providing an integer function such as IOR(A,B) that performs an '''or''' on integers A and B. Instead of doing so, the function overwrites its invocation by placing in-line code that performs A '''or''' B, then returns not to its return address but to where it was invoked from so as to compute the result.
 
====Away, and maybe, back====
Similarly to escaping from a subroutine, within a DO-loop, a GO TO might jump out of the loop(s) - perhaps for good reason. More interesting is the possibility of jumping ''into'' a DO-loop's scope, possibly after jumping out - who knows what its index variable might have been changed to. This is considered poor form by others not writing such code and some compilers will reject any attempts. With the F77 introduction of IF ... THEN ... ELSE ... END IF constructions, jumping out of a block is still acceptable but jumping in is frowned on (even if only from the THEN clause to some part of its ELSE clause) and may be prevented.
 
F90 offers a more decorous means for exiting DO-loops, including the additional DO WHILE loop, via the statements CYCLE and EXIT - the text "GO TO" does not appear as such, but the effect is the same. The CYCLE option means abandoning further statements within the block to test afresh the iteration condition, while EXIT means ending the iteration as if it had completed. Further syntax allows some compiler checking, as follows: <syntaxhighlight lang="fortran"> XX:DO WHILE(condition)
statements...
NN:DO I = 1,N
statements...
IF (...) EXIT XX
IF (...) CYCLE NN
statements...
END DO NN
END DO XX </syntaxhighlight>
A DO-loop can be given a label such as XX (which is ''not'' in the numeric-only label area of fixed source format Fortran, and the syntax highlghter has missed yet another trick of Fortran syntax) and its corresponding END DO can be given a label also: the compiler checks that they match and some programmer errors might thereby be caught. With such labels in use, the CYCLE and EXIT statements can name the loop they are intended for, so that CYCLE NN steps to the next iteration for <code>I</code> (as if it were a GO TO the END DO having its label as a suffix) while the EXIT XX exits both the numeric DO-LOOP and the DO-WHILE loop - without such labels only the innermost loop is affected and one can lose track. These labels must not be the name of any other entity in the source, and specifically not the name of the variable of the DO-LOOP concerned. Thus, if there are many DO I = 1,N loops, each must have its own label. There is unfortunately no equivalent to <code>NEXT I</code> as in BASIC instead of <code>END DO</code>so as to be clear just which DO-LOOP is being ended and for which index variable.
 
====Not returning at all====
In for example Fortran IV, as on the IBM1130, a <code>CALL EXIT</code> stopped the run, which is to say, it "exited" to the operating system. As distinct from STOP which stopped the flow by stopping the cpu. Another no-return was provided by the likes of <code>CALL LINK(PHASE2)</code> where PHASE2 was not a text string in quotes. This caused the flow of execution to abandon the current programme and the operating system would load and run a programme called PHASE2. Code was loaded from low memory upwards, while storage in COMMON was assigned from high memory downwards and so long as desired data were not damaged by the new load, its processing would continue. Thus, if some data required a great deal of complex analysis and there was insufficient memory available to hold all the data plus all the code, it might be possible to split the processing into PHASE1 and PHASE2, etc.
 
===Interruptions to the flow===
More potent than RETURN is STOP, which ends the flow of execution there and then - without the need to signal some sort of "disaster" status so that each level of a nest of routines would return to its caller. Early Fortran also allowed STOP ''n'' where ''n'' was a number such as 303 and this value might be displayed on the computer's console display register in bright lights, or be printed in the job log, or on the standard output device. A later extension was STOP "message", but alas the message is only a fixed text, one can't devise a custom report such as "307 values! Limit is 300" as via <code>STOP N," values! Limit is ",NMAX</code>
 
Instead of STOP, there is PAUSE with the same syntax. The flow of execution would pause (that is, the entire computer would come to a stop in the days when one job only would run at a time), to be resumed with the next statement on the pressing of a button on the computer console for instance after the message "Attach output tape", or, ... the operator could via controls on the console inspect memory (on the decimal IBM1620, even floating-point numbers were easily parsed), modify memory, and cause execution to resume at some other (any other) chosen address...
 
===Flowcharts?===
A classic aid to design and analysis is a flowchart diagram, and there exist systems which will read the source code of a programme and draw its flowchart (on a graph plotter, say) with the various pieces of code appearing in blocks linked by lines showing the flow. Considering all the above (and not forgetting the arithmetic-IF and IF ... THEN ... ELSE ... ENDIF statements, DO-loops, DO WHILE loops and the SELECT and WHERE ... ELSEWHERE statements), this is no simple challenge.
 
===Reaction===
There is a famous letter by Edsger Dijkstra, titled ''Go To Statement Considered Harmful'', published in the March 1968 Communications of the ACM.
====Response====
A thorough analysis of the problem appears in ''Structured Programming with'' '''go to''' ''Statements'' by Donald E. Knuth, December 1974. There's even mention of decision tables.
 
 
=={{header|FreeBASIC}}==
FreeBASIC has GOSUB and GOTO but they are obsolete.
 
Still, they are available when using the -lang qb dialect.
This dialect provides the best support for the older QuickBASIC code.
<syntaxhighlight lang="freebasic">
'$lang: "qb"
 
Gosub subrutina
 
bucle:
Print "Bucle infinito"
Goto bucle
End
 
subrutina:
Print "En subrutina"
Sleep 100
Return
Sleep
</syntaxhighlight>
 
 
=={{header|Gambas}}==
'''[https://gambas-playground.proko.eu/?gist=64e4e68b1c6ce73341d08ba2d9333c07 Click this link to run this code]'''
<syntaxhighlight lang="gambas">Public Sub Main()
Dim siCount As Short
 
LOOPIT:
 
Print siCount;;
Inc siCount
If siCount > 100 Then Quit
Goto LoopIt
 
End</syntaxhighlight>
Output:
<pre>
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77
78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100
</pre>
 
=={{header|Go}}==
Not covered here::
Line 365 ⟶ 979:
===Goto===
Go has goto and labels. The following is an infinite loop:
<langsyntaxhighlight lang="go">func main() {
inf:
goto inf
}</langsyntaxhighlight>
Gotos can jump forward or backward within a function but they have some restrictions. They cannot jump into any block from outside the block, and they cannot cause any variable to come into scope.
 
===Function call===
Function call works as it does in most languages, transferring execution to to the called function, and returning execution to the following statement upon return from the called function.
Line 375 ⟶ 991:
 
The defer statement sets a function or method to be executed upon return from the enclosing function. This is useful when a function has multiple returns. The classic example is closing a file:
<langsyntaxhighlight lang="go">import "os"
 
func processFile() {
Line 392 ⟶ 1,008:
// more processing
// f.Close() will get called here too
}</langsyntaxhighlight>
 
===Goroutines===
Goroutines are Go’s take on lightweight threads. A goroutine is started with a go statement, which looks like “go” preceding a function call. When the go statement executes, a new goroutine is created, execution in the new goroutine starts with a call to the function named in the go statement, and execution in the calling goroutine continues without interruptionconcurrently. (The main thread of execution is a goroutine itself.)
 
The following program prints a mix of 1’s and 0’s.
<langsyntaxhighlight lang="go">package main
 
import "fmt"
Line 413 ⟶ 1,029:
fmt.Println("0")
}
}</langsyntaxhighlight>
 
A goroutine terminates upon return from the function called in the go statement. Unlike with a regular function call however, it cannot return a value--the calling goroutine has long continued and there is nothing waiting for a return value.
 
Goroutines may not be able to communicate by returning values, but they have other ways. Principal is passing data through channels. Channel operations affect execution when they yield the processor, allowing other goroutines to run, but this does not normally alter flow of execution. The one exception is when channel operations are used in a select statement. A simple use,
<langsyntaxhighlight lang="go">func answer(phone1, phone2 chan int) {
select {
case <-phone1:
Line 425 ⟶ 1,041:
// talk on phone two
}
}</langsyntaxhighlight>
Syntax is strongly reminiscent of the switch statement, but rules for flow control are very different. Select will block if no channel operation is possible. If one is possible, it will execute that case. If multiple operations are possible, it will pick one at random.
===Process initialization===
A complete program must have exactly one function named main, which is called on program start up. In addition, a program can have any number of functions named init. Thesewhich are called before main,. but otherwisePackage invariables unspecifiedare orderinitialized before init functions or main are called.
 
=={{header|GW-BASIC}}==
<syntaxhighlight lang ="qbasic">10010 PRINTLET "Endless loop"a=1
20 IF a=2 THEN PRINT "This is a conditional statement"
110 GOTO 100</lang>
30 IF a=1 THEN GOTO 50: REM a conditional jump
40 PRINT "This statement will be skipped"
50 PRINT ("Hello" AND (1=2)): REM This does not print
100 PRINT "Endless loop"
110 GOTO 100:REM an unconditional jump</syntaxhighlight>
 
=={{header|Haskell}}==
Line 438 ⟶ 1,059:
In the context of normal, functional-style code, there are no flow-control statements, because explicit flow control is imperative. A monad may offer flow control; what kinds are available depends on the monad. For example, the [http://haskell.org/haskellwiki/New_monads/MonadExit <code>ExitT</code> monad transformer] lets you use the <code>exitWith</code> function to jump out a block of statements at will.
 
<langsyntaxhighlight lang="haskell">import Control.Monad
import Control.Monad.Trans
import Control.Monad.Exit
Line 449 ⟶ 1,070:
when (x == 3 && y == 2) $
exitWith ()
putStrLn "Done."</langsyntaxhighlight>
 
=={{header|HicEst}}==
[http://www.HicEst.com More on HicEst's ALARM function]
<langsyntaxhighlight lang="hicest">1 GOTO 2 ! branch to label
 
2 READ(FIle=name, IOStat=ios, ERror=3) something ! on error branch to label 3
Line 469 ⟶ 1,090:
8 y = LOG( 0 , *9) ! on error branch to label 9
 
9 ALARM( 999 ) ! quit HicEst immediately</langsyntaxhighlight>
 
=={{header|Icon}} and {{header|Unicon}}==
Line 484 ⟶ 1,105:
'''break expr'''<br>
Default value of ''expr'' is the null value ''&amp;null''. This operator breaks out of the enclosing loop, yielding the expression as the result of the loop. Normally loops yield a failure ie no result, so you can write code like this:
<langsyntaxhighlight lang="icon">
if x := every i := 1 to *container do { # * is the 'length' operator
if container[i] ~== y then
Line 494 ⟶ 1,115:
else
write("did not find an item")
</syntaxhighlight>
</lang>
The expression given to ''break'' can be another ''break'', which effectively lets you break out of two levels of loop. Finally, the expression given to break can be the ''next'' command; for example
<langsyntaxhighlight lang="icon">
break break next
</syntaxhighlight>
</lang>
breaks out of two levels of loop and re-enters the top of the third-level enclosing loop.
 
Line 506 ⟶ 1,127:
'''fail'''<br>
Causes the the enclosing procedure to terminate without returning value. This is different from returning void or a null value that many other languages do when the code does not return an actual value. For example, in
<langsyntaxhighlight lang="icon">
x := ftn()
</syntaxhighlight>
</lang>
The value of x will not be replaced if ftn() issues the ''fail'' command. If ftn fails, then Goal-Directed Evaluation will also fail the assignment, therefore x is not assigned a new value. If the flow of control through a procedure falls off the end, the procedure implicitly fails.
 
Line 521 ⟶ 1,142:
'''error trapping'''<br>
The keyword &amp;error is normally zero, but if set to a positive value, this sets the number of fatal errors that are tolerated and converted to expression failure; the value of &amp;error is decremented if this happens. Therefore the now-common TRY-CATCH behaviour can be written as:
<langsyntaxhighlight lang="icon">
&error := 1
mayErrorOut()
Line 530 ⟶ 1,151:
handleError(&errornumber, &errortext, &errorvalue) # keyword values containing facts about the failure
}
</syntaxhighlight>
</lang>
Various idiomatic simplifications can be applied depending on your needs.
 
'''error throwing'''<br>
Errors can be thrown using the function
<langsyntaxhighlight lang="icon">
runerr(errnumber, errorvalue) # choose an error number and supply the offending value
</syntaxhighlight>
</lang>
 
=={{header|IDL}}==
Line 543 ⟶ 1,164:
===goto===
 
<langsyntaxhighlight lang="idl">test:
..some code here
goto, test</langsyntaxhighlight>
 
(This is almost never used)
Line 551 ⟶ 1,172:
===on_error===
 
<syntaxhighlight lang ="idl">on_error, test</langsyntaxhighlight>
 
(This resumes at the label <tt>test</tt> if an error is encountered)
Line 557 ⟶ 1,178:
===on_ioerror===
 
<syntaxhighlight lang ="idl">on_ioerror, test</langsyntaxhighlight>
 
(Same as <tt>on_error</tt>, but for EOFs and read-errors and such)
Line 563 ⟶ 1,184:
===break===
 
<syntaxhighlight lang ="idl">break</langsyntaxhighlight>
 
immediately terminates the innermost current loop (or <tt>if</tt> or <tt>case</tt> etc)
Line 569 ⟶ 1,190:
===continue===
 
<syntaxhighlight lang ="idl">continue</langsyntaxhighlight>
 
immediately starts the next iteration of the current innermost loop
Line 577 ⟶ 1,198:
Control structures should usually [but not always] be avoided in J. J's primitives already provide iteration and selection.
 
For example, here's an example of a program which loops over a sequence of integers, multiplying them by two (j's default prompt is 3 spaces, which makes line-at-a-time copy-and-paste simple, and the result here is displayed on the following line):
<langsyntaxhighlight lang="j"> 2 * 1 2 3
2 4 6</langsyntaxhighlight>
 
That said, J's control structures are documented at http://www.jsoftware.com/help/dictionary/ctrl.htm So, if you want to perform this same operation using a while loop, or a goto, you can do so. It's just... often not a good idea (but sometimes they are indispensable).
Line 585 ⟶ 1,206:
=={{header|Java}}==
"goto" is a reserved keyword in Java; but you cannot use it. There are currently no goto statements.
 
Java does provide two other statements that provide flow control: <tt>break</tt> and <tt>continue</tt>.
 
===break===
The <tt>break</tt> statement can be used to terminate a <tt>case</tt> clause in a <tt>switch</tt> statement and to terminate a <tt>for</tt>, <tt>while</tt> or <tt>do-while</tt> loop. In loops, a <tt>break</tt> can be ''labeled'' or ''unlabeled''.
 
<syntaxhighlight lang="java">switch (xx) {
case 1:
case 2:
/* 1 & 2 both come here... */
...
break;
case 4:
/* 4 comes here... */
...
break;
case 5:
/* 5 comes here... */
...
break;
default:
/* everything else */
break;
}
 
for (int i = 0; i < 10; ++i) {
...
if (some_condition) { break; }
...
}
 
_Time_: do {
for (int i = 0; i < 10; ++i) {
...
if (some_condition) { break _Time_; /* terminate the do-while loop */}
...
}
...
} while (thisCondition);</syntaxhighlight>
 
===continue===
The <tt>continue</tt> statement skips the current iteration of a <tt>for</tt>, <tt>while</tt>, or <tt>do-while</tt> loop. As with <tt>break</tt> the <tt>continue</tt> statement can be ''labeled'' or ''unlabeled'' to allow iterating a loop level other than the current one in nested loops.
 
<syntaxhighlight lang="java">while (condition) {
...
if (someCondition) { continue; /* skip to beginning of this loop */ }
...
}
 
top: for (int 1 = 0; i < 10; ++i) {
...
middle: for (int j = 0; j < 10; ++j) {
...
bottom: for (int k = 0; k < 10; ++k) {
...
if (top_condition) { continue top; /* restart outer loop */ }
...
if (middle_condition) { continue middle; /* restart middle loop */ }
...
if (bottom_condition) { continue bottom; /* restart bottom loop */ }
...
if (bottom_condition) { continue; /* this will also restart bottom loop */ }
...
}
...
}
....
}</syntaxhighlight>
 
=={{header|JavaScript}}==
* <code>'''return'''</code> from a function ([http://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Statements/return])
* <code>'''yield'''</code> from a generator function ([https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/yield])
* <code>'''yield*'''</code> from a generator function ([https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/yield*])
* <code>'''await'''</code> from an async function ([https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await])
* loop control with <code>'''break''' [label]</code> ([http://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Statements/break]) and <code>'''continue''' [label]</code> ([http://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Statements/continue])
* exceptions with <code>'''throw'''</code> ([http://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Statements/throw]) and <code>'''try ... catch ... finally ...'''</code> ([http://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Statements/try...catch])
 
=={{header|jq}}==
 
jq 1.5 introduced `break` and `label` keywords for defining backtracking points. These are used to terminate a generator before completion. Here is a contrived example that illustrates the main points:
<pre>$ jq -n '1, (2 | label $foo | debug | 3 | break $foo | debug), 4'
1
["DEBUG:",2]
4</pre>
 
Here is an example from the standard library:
<syntaxhighlight lang="jq"># Emit at most one item from the stream generated by g:
def first(g): label $out | g | ., break $out;</syntaxhighlight>
 
=={{header|Julia}}==
Julia provides the @goto and @label macros for goto within functions. In addition, the "break" keyword is used for jumping out of a single loop, throw() of an exception can be used to jump out of a try() statement's code, and the assert() and exit() functions can be used to terminate a program.
<syntaxhighlight lang="julia">
function example()
println("Hello ")
@goto world
println("Never printed")
@label world
println("world")
end
</syntaxhighlight>
 
=={{header|Kotlin}}==
 
Kotlin does not have a 'goto' statement but does have 'break' and 'continue' statements to jump out of or continue with the next iteration of a loop. The 'labelled' versions of these statements have already been described at [[Jump_anywhere#Kotlin]] and so only the basic versions are described in this task which jump out or continue with the nearest enclosing loop.
 
Kotlin also has a 'throw' statement which throws (or rethrows) an exception.
 
Here are some examples:
<syntaxhighlight lang="scala">// version 1.0.6
 
fun main(args: Array<String>) {
for (i in 0 .. 2) {
for (j in 0 .. 2) {
if (i + j == 2) continue
if (i + j == 3) break
println(i + j)
}
}
println()
if (args.isNotEmpty()) throw IllegalArgumentException("No command line arguments should be supplied")
println("Goodbye!") // won't be executed
}</syntaxhighlight>
 
{{out}}
<pre>
c:\kotlin-compiler-1.0.6>java -jar control_flow.jar arg1 arg2
0
1
1
 
Exception in thread "main" java.lang.IllegalArgumentException: No command line arguments should be supplied
at Control_throwKt.main(control_throw.kt:12)
</pre>
 
=={{header|Lua}}==
Lua has the <code>break</code>-command to exit loops.
<langsyntaxhighlight lang="lua">i = 0
while true do
i = i + 1
if i > 10 then break end
end</langsyntaxhighlight>
===Tail calls as GOTOs===
The following code - though obviously a useless infinite loop - will '''not''' cause a stack overflow:
<syntaxhighlight lang="lua">function func1 ()
return func2()
end
 
function func2 ()
return func1()
end
 
func1()</syntaxhighlight>
This is because Lua supports proper tail recursion. This means that because something being returned is necessarily the last action in a function, the interpreter treats a function call in this 'tail' position much like a GOTO in other languages and does not create a new stack level.
 
=={{header|M2000 Interpreter}}==
M2000 has labels, Goto, Gosub, On Goto, On Gosub, and can use numeric labels immediate at Then and Else clause. Goto can be used inside a block, or structure which may have hidden block. We can't use Goto to jump to outer module (calling module). Also we can't start a module from a label.
 
Gosub level controlled by Recursion.Limit (which is 10000 by default but we can change it to anything, like 1000000, using Recursion.limit 1000000), depends only from size of memory for 32bit applications (2Gbyte).
 
Every is a block structure for execution code synchronized by timer. If code exit execution time of block's constant time, executed later at same phase. There are three more statements for tasks, AFTER, THREAD and MAIN.TASK for executing code based on time in sequential of concurrent fashion, not shown here.
 
We can use Error "name of error" to produce error and we can catch it through a Try block.
 
 
====Use of Labels====
<syntaxhighlight lang="m2000 interpreter">
Module Inner {
long x=random(1, 2)
on x goto 90, 100
090 print "can print here if is "+x // if x=1
100 Print "ok"
gosub 500
alfa: // no statement here only comments because : is also statement separator
print "ok too"
integer c
Every 100 { // every 100 miliseconds this block executed
c++
gosub printc
if c>9 then 200
}
print "no print here"
200 Gosub exitUsingGoto
Every 100 { // every 100 miliseconds this block executed
c++
gosub printc
if c>19 then exit
}
gosub 500
try ok {
on x gosub 400, 1234
}
if ok else print error$ // sub not found (if x=2)
goto 1234 ' not exist so this is an exit from module
400 print "can print here if is "+x // if x=1
end
printc:
Print c
return
500 Print "exit from block using exit" : return
exitUsingGoto:
Print "exit from block using goto"
return
}
Inner
</syntaxhighlight>
 
====Use of Call Back function====
M2000 has no yield statement/function. We can use a call back function to get results, before a module exit. The call back function act as code in the calling module (has same scope), but has a difference: we can't use goto/gosub out of it
 
<syntaxhighlight lang="m2000 interpreter">
module outer {
static m as long=100 // if m not exist created
module count (&a(), b) {
long c=1
do
if b(c) then exit
call a(c)
c++
always
}
long z, i=100
// function k used as call back function, through lazy$()
function k {
read new i
print i // print 1 and 2
z+=i
m++
}
count lazy$(&k()), (lambda (i)->i>=3)
print z=3, i=100, m
}
clear // clear variables (and static variables) from this point
outer // m is 102
outer // m is 104
outer // m is 106
</syntaxhighlight>
 
====Using Break/Continue in Select Case====
Normally the Break statement break module (exit from module) or a Try { } block. Normally Continue is like exit in ordinary blocks or a new iteration for loop structures. For a Select case, a Break make the execution of other blocks from other cases to executed until "case else" or a continue statement. Both ends goes to end select. So break works in reverse of c's break. Without block { } in cases, Break and Continue works for the outer block (like normal break and continue). We can use Goto in cases, to exit select/end select structure, using or not using block in cases. Gosub can be used as usual everywhere.
 
<syntaxhighlight lang="m2000 interpreter">
Module checkSelect {
long m, i, k
for k=1 to 10
m=10
i=random(5, 10)
select case i
case <6
print "less than 6"
case 6
{
m++: break // break case block, and continue to next block
}
case 7
{
m++: break
}
case 8
{
m++: continue // exit after end select
}
case 9
print "is 9"
case else
print "more than 9"
end select
print m, i
next
}
checkSelect
</syntaxhighlight>
 
=={{header|Mathematica}} / {{header|Wolfram Language}}==
Relevant functions are:
 
Line 619 ⟶ 1,501:
Throw[] causes a non-local jump to a specified Catch[]
 
=={{header|MATLAB}} / {{header|Octave}}==
<syntaxhighlight lang="matlab">
try
% do some stuff
catch
% in case of error, continue here
end
</syntaxhighlight>
 
=={{header|Maxima}}==
<langsyntaxhighlight lang="maxima">/* goto */
block(..., label, ..., go(label), ...);
 
Line 628 ⟶ 1,518:
 
/* error trapping */
errcatch(..., error("Bad luck!"), ...);</langsyntaxhighlight>
 
=={{header|MUMPS}}==
===GOTO / G===
<p>JumpsThe GOTO command jumps to a label. If the label is not in the current routine, it is necessary to include the circumflex and routine name. <syntaxhighlight lang="mumps">GOTO LABEL^ROUTINE</syntaxhighlight>. This does not affect the subroutine stack, only the program pointer.</p><langsyntaxhighlight MUMPSlang="mumps">GOTO THERE</langsyntaxhighlight>
 
===HALT / H===
<p>Halt and Hang have the same abbreviation, i.e. "H" but (as a mnemonic) Halt takes no arguments. Halt stops the current process, and clears all Locks and devices in Use.
On the Cache variant of MUMPS, there is a $HALT special variable that can be set, the value of the $HALT special variable is a routine that is called before cleaning up (in effect, a specialized final error trap).</p>
<langsyntaxhighlight MUMPSlang="mumps"> Read "Do you really wish to halt (Y/N)?",Q#1
IF Q="Y"!Q="y" HALT</langsyntaxhighlight>
 
===JOB / J===
<p> The JOB command starts another MUMPS job starting at a label. If the label is not in the current routine, it is necessary to include the circumflex and routine name. <syntaxhighlight lang="mumps">JOB LABEL^ROUTINE</syntaxhighlight>. <syntaxhighlight lang="mumps">JOB THERE</syntaxhighlight> This does not affect the subroutine stack, nor the program pointer in the current job. Since MUMPS is a multi-processing (rather than multi-threading) language, the new job is independent of the current job.</p>
<syntaxhighlight lang="mumps"> JOB LABEL^ROUTINE</syntaxhighlight>
 
 
===QUIT / Q===
<p>Exits a loop, or routine. It decreases the stack level. It can return a value to a calling routine if there is a value after it.</p><p>Quit is one of the commands that requires two spaces after it if it is followed in a line by more commands.</p>
<langsyntaxhighlight MUMPSlang="mumps">FOR I=1:1:1 QUIT:NoLoop DO YesLoop
QUIT Returnvalue</langsyntaxhighlight>
===XECUTE / X===
<p>eXecute acts as if it were a one line Do command. Its argument must be a string of valid MUMPS code, and it performs that code in a new stack level. There is an implied Quit at the end of each eXecute's argument string.</p><langsyntaxhighlight MUMPSlang="mumps"> SET A="SET %=$INCREMENT(I)"
SET I=0
XECUTE A
WRITE I</langsyntaxhighlight>
The above block will output "1".
<math>Insert formula here</math>
Line 655 ⟶ 1,551:
 
Exceptions can also be used to transfer control from a '''try''' block to a '''catch''' block.
 
=={{header|NetRexx}}==
NetRexx doesn't have a <tt>GOTO</tt> instruction and unlike [[#REXX|Rexx]] the <tt>SIGNAL</tt> instruction is only used to throw exceptions.
 
Like [[#REXX|Rexx]] however, NetRexx provides the <tt>LEAVE</tt> and <tt>ITERATE</tt> instructions.
 
===LEAVE===
The <tt>LEAVE</tt> instruction causes immediate exit from one or more <tt>DO</tt>, <tt>SELECT</tt> or <tt>LOOP</tt> constructs.
 
<syntaxhighlight lang="netrexx">loop xx = 1 to 10
if xx = 1 then leave -- loop terminated by leave
say 'unreachable'
end</syntaxhighlight>
 
A ''<tt>name</tt>'' parameter can be provided to direct <tt>LEAVE</tt> to a specific end of block (as defined by a <tt>LABEL</tt> option or in the case of a controlled <tt>LOOP</tt> the control variable of the loop.
 
<syntaxhighlight lang="netrexx">loop xx = 1 to 10 -- xx is the control variable
...
loop yy = 1 to 10 -- yy is the control variable
...
if yy = 3 then leave xx -- xx loop terminated by leave
if yy = 4 then leave yy -- yy loop terminated by leave
...
end
...
end xx
 
loop label xlabel xx = 1 to 10 -- xx is still the control variable but LABEL takes precidence
...
loop yy = 1 to 10 -- yy is the control variable
...
if yy = 3 then leave xlabel -- xx loop terminated by leave
...
end yy
...
end xlabel
 
do label FINIS
say 'in do block'
if (1 == 1) then leave FINIS
say 'unreachable'
signal Exception("Will never happen")
catch ex = Exception
ex.printStackTrace()
finally
say 'out of do block'
end FINIS
 
loop vv over ['A', 'B']
select label selecting case vv
when 'A' then do; say 'A selected'; say '...'; end
when 'B' then do;
say 'B selected';
if (1 == 1) then leave selecting;
say '...';
end
otherwise do; say 'nl selection'; say '...'; end
end selecting
end vv</syntaxhighlight>
 
===ITERATE===
The <tt>ITERATE</tt> instruction alters flow of control within a <tt>LOOP</tt> construct.
On encountering an <tt>ITERATE</tt> instruction, execution of the loop body is terminated and control is passed directly back to the top of the loop just as though the last clause in the body of the loop had been executed.
 
As with <tt>LEAVE</tt> an optional ''<tt>name</tt>'' parameter can be supplied to direct the instruction to a loop level outside the current level.
<syntaxhighlight lang="netrexx">loop fff = 0 to 9
...
loop xx = 1 to 3
...
if fff > 2 then iterate fff
...
end
...
end fff</syntaxhighlight>
 
=={{header|Nim}}==
===Labeled Break & Continue===
Break and continue can be used with block labels to jump out of multiple loops:
<syntaxhighlight lang="nim">block outer:
for i in 0..1000:
for j in 0..1000:
if i + j == 3:
break outer</syntaxhighlight>
 
===Try-Except-Finally===
<syntaxhighlight lang="nim">var f = open "input.txt"
try:
var s = readLine f
except IOError:
echo "An error occurred!"
finally:
close f</syntaxhighlight>
 
=={{header|OCaml}}==
Line 660 ⟶ 1,648:
An OCaml user can simulate flow control using exceptions:
 
<langsyntaxhighlight lang="ocaml">exception Found of int
 
let () =
Line 669 ⟶ 1,657:
print_endline "nothing found"
with Found res ->
Printf.printf "found %d\n" res</langsyntaxhighlight>
 
=={{header|Oforth}}==
 
Oforth does not have goto statement.
 
break allows to break the current loop :
<syntaxhighlight lang="oforth">break</syntaxhighlight>
 
continue allows to immediately start a new iteration :
<syntaxhighlight lang="oforth">continue</syntaxhighlight>
 
perform is a method that transfer execution to the runnable on top of the stack, then returns :
<syntaxhighlight lang="oforth">perform</syntaxhighlight>
 
=={{header|Oz}}==
Line 676 ⟶ 1,676:
 
The <code>case</code> statement can be used for [[Pattern Matching]], but also like a switch statement in C:
<langsyntaxhighlight lang="oz">case {OS.rand} mod 3
of 0 then {Foo}
[] 1 then {Bar}
[] 2 then {Buzz}
end</langsyntaxhighlight>
 
The Lisp-influenced [http://www.mozart-oz.org/home/doc/loop/index.html for-loop] is very powerful and convenient to use.
Line 696 ⟶ 1,696:
As an example for <code>choice</code>, a simple, but stupid way to solve the equation 2*X=18. We assume that the solution is somewhere in the interval 8-10, but we do not quite know what exactly it is.
 
<langsyntaxhighlight lang="oz">declare
proc {Stupid X}
choice
Line 710 ⟶ 1,710:
end
in
{Show {SearchOne Stupid}}</langsyntaxhighlight>
 
{{out}}
Output:
<pre>
choosing 8
Line 720 ⟶ 1,720:
 
=={{header|PARI/GP}}==
Flow control structures include function calling and returning, <code>error</code>/<code>trap</code>, <code>next</code>/<code>break</code>, <code>alarm</code>, and the various loops.
and the various loops.
 
=={{header|Pascal}}==
===goto===
<langsyntaxhighlight lang="pascal">label
jumpto;
begin
Line 733 ⟶ 1,734:
goto jumpto;
...
end;</langsyntaxhighlight>
 
===exception===
<langsyntaxhighlight lang="pascal">try
Z := DoDiv (X,Y);
except
on EDivException do Z := 0;
end;</langsyntaxhighlight>
 
===Halt===
Halt stops program execution and returns control to the calling program. The optional argument
Errnum specifies an exit value. If omitted, zero is returned.
<syntaxhighlight lang ="pascal">procedure halt(errnum: Byte);</langsyntaxhighlight>
 
===Exit===
Line 752 ⟶ 1,753:
The optional argument X allows to specify a return value, in the case Exit
is invoked in a function. The function result will then be equal to X.
<langsyntaxhighlight lang="pascal">procedure exit(const X: TAnyType)</langsyntaxhighlight>
 
Calls of functions/procedures as well as breaks and continues in loops are described in the corresponding tasks.
Line 762 ⟶ 1,763:
Goto is typically looked down upon by most Perl programmers
 
<langsyntaxhighlight lang="perl">FORK:
# some code
goto FORK;</langsyntaxhighlight>
 
=={{header|Phix}}==
{{libheader|Phix/basics}}
===goto===
In 0.8.4+ Phix finally has a goto statement:
<!--<syntaxhighlight lang="phix">-->
<span style="color: #008080;">without</span> <span style="color: #008080;">js</span> <span style="color: #000080;font-style:italic;">-- (no goto in JavaScript)</span>
<span style="color: #008080;">procedure</span> <span style="color: #000000;">p</span><span style="color: #0000FF;">()</span>
<span style="color: #7060A8;">goto</span> <span style="color: #0000FF;">:</span><span style="color: #000000;">but_print</span>
<span style="color: #7060A8;">puts</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"This will not be printed...\n"</span><span style="color: #0000FF;">)</span>
<span style="color: #0000FF;">::</span><span style="color: #000000;">but_print</span>
<span style="color: #7060A8;">puts</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"...but this will\n"</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
<span style="color: #000000;">p</span><span style="color: #0000FF;">()</span>
<!--</syntaxhighlight>-->
Imposing a self-policed rule that all jumps must be forward (or equivalently all backward, but never mixed) is recommended.
 
Phix imposes the following limitations on the use of goto statements:<br>
A goto statement must be in the same function as the label it is referring.<br>
The goto statement is not supported in top level code, outside of a routine definition.<br>
There are no computed, assigned, or multiple target forms of the goto statement.<br>
Goto may not be used and labels may not be defined anywhere inside a try/catch statement.<br>
Jumping over variable initialisation will, naturally, leave the variable unassigned.<br>
A goto can optionally refer to label or :label - they mean the same thing.<br>
(Technically the colon-less variant is shorthand for the formal with-colon label reference.)<br>
A label, which adheres to the usual identifier rules, is defined by preceding it with a double colon.
 
Note that a goto statement, or inline assembly (a goto statement is implemented using fragments of auto-generated inline assembly) will cause the compiler to abandon certain optimisation efforts, in particular type inferencing and constant propagation, which can result in a larger and slower program.
 
Previous versions had no hll goto statement, however the following work around was (and still is) available:
<syntaxhighlight lang="phix">without js
#ilASM{ jmp :label }
...
#ilASM{ ::label }</syntaxhighlight>
In top level code, label scope is restricted to a single ilASM construct,
but within a routine, the scope is across all the ilasm in that routine.
 
There is quite deliberately no support for jumping from the middle of one
routine into another: without a frame, then quite simply parameters and
local variables have not been allocated and cannot be used/referenced.
 
It is also possible to declare global labels, which are superficially similar:
<syntaxhighlight lang="phix">without js
#ilASM{ call :%label }
...
#ilASM{ jmp :skip
:%label
ret
::skip }</syntaxhighlight>
Global labels cannot be declared inside a routine, and as shown (almost always)
require a skip construct. It is up to the programmer to ensure global labels
are unique across the entire application.
Note that global labels are both declared and referenced with ":%", whereas
local labels are declared with "::" but referenced with ":".
 
&lt;it was claimed&gt;
Making "goto" somewhat more difficult to type in this manner ensures that
it is far less likely to be abused, and discourages newbie programmers
from adopting it as a weapon of choice, as usually(/always) happens with
a hll goto.
&lt;/it was claimed&gt;
 
===continue===
Personally I must agree with Douglas Crockford who says "I have never seen a piece of code that was not improved by refactoring it to remove the continue statement".<br>
Causes the next interation of the immediately surrounding loop to begin immediately, with any condition evaluated normally. The following two loops behave identically:
<!--<syntaxhighlight lang="phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #000000;">100</span> <span style="color: #008080;">do</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">a</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]=</span><span style="color: #000000;">0</span> <span style="color: #008080;">then</span> <span style="color: #008080;">continue</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #0000FF;">...</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #000000;">100</span> <span style="color: #008080;">do</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">a</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]!=</span><span style="color: #000000;">0</span> <span style="color: #008080;">then</span>
<span style="color: #0000FF;">...</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<!--</syntaxhighlight>-->
 
===exit===
causes immediate termination of the immediately surrounding for or while loop, with control passing to the first statement after the loop, eg:
<!--<syntaxhighlight lang="phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #000000;">100</span> <span style="color: #008080;">do</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">a</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]=</span><span style="color: #000000;">x</span> <span style="color: #008080;">then</span>
<span style="color: #000000;">location</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">i</span>
<span style="color: #008080;">exit</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<!--</syntaxhighlight>-->
 
===break===
Terminate a switch statement. fallthrough is the opposite, overriding an implicit break between cases.<br>
Note that JavaScript uses break for both switch and loop constructs, therefore pwa/p2js imposes additional rules to ensure compatibility, ie sufficiently nested/anything JavaScript can do is fine, but while desktop/Phix allows a loop to directly exit a switch and vice versa, the transpiler terminates in error when it detects any such attempts.
 
===return===
Exits the current routine. Needs a value to return if used inside a function or type.
 
===abort, crash, throw===
Terminate the entire application immediately, unless caught by a containing try/catch statement.<br>
Technically it is possible to use these to effect control flow, albeit in a grossly inefficient manner.
 
===tasks and threads===
Phix supports both multitasking and multithreading. In multitasking, at most one task is currently running, so no locking is
required, and the application explicitly invokes task_yield to indicate when it is safe to switch between tasks. Multithreading
is potentially much trickier, everything that could be accessed concurrently must be locked - however when one thread is stalled,
perhaps waiting for a network response, the other threads are unaffected.
 
=={{header|PHP}}==
Line 772 ⟶ 1,880:
Introduced in PHP 5.3, PHP now has a goto flow-control structure, even though most PHP programmers see it as a bad habbit (may cause spaghetti-code).
 
<langsyntaxhighlight lang="php"><?php
goto a;
echo 'Foo';
Line 778 ⟶ 1,886:
a:
echo 'Bar';
?></langsyntaxhighlight>
{{out}}
Output:
<pre>Bar</pre>
 
Line 828 ⟶ 1,936:
 
=={{header|PL/I}}==
<syntaxhighlight lang="pl/i">
<lang PL/I>
LEAVE
The LEAVE statement terminates execution of a loop.
Line 857 ⟶ 1,965:
It can also be used to transfer control to any one of an array of
labelled statements. (This form is superseded by SELECT, above.)
[GO TO can also be spelled as GOTO].
</lang>
</syntaxhighlight>
 
=={{header|Pop11}}==
Line 864 ⟶ 1,973:
quitloop with argument exits from nested loops:
 
<langsyntaxhighlight lang="pop11">while condition1 do
while condition2 do
if condition3 then
Line 870 ⟶ 1,979:
endif;
endwhile;
endwhile;</langsyntaxhighlight>
 
above quitloop(2) exits from both loops.
Line 879 ⟶ 1,988:
nested loops:
 
<langsyntaxhighlight lang="pop11">while condition1 do
while condition2 do
if condition3 then
Line 886 ⟶ 1,995:
endwhile;
endwhile;
l:;</langsyntaxhighlight>
 
Another use is to implement finite state machines:
 
<langsyntaxhighlight lang="pop11">state1:
DO_SOMETHING();
if condition1 then
Line 905 ⟶ 2,014:
...
stateN:
....</langsyntaxhighlight>
 
Pop11 goto is a nonlocal one, so "jump out" from a chain of procedure calls:
 
<langsyntaxhighlight lang="pop11">define outer();
define inner(n);
if n = 0 then
Line 918 ⟶ 2,027:
inner(5);
final:;
enddefine;</langsyntaxhighlight>
 
This is useful to exit early from successful recursive search, and for exception handling.
Line 926 ⟶ 2,035:
go_on is a multiway jump
 
<langsyntaxhighlight lang="pop11">go_on expression to lab1, lab2, ..., labN else elselab ;</langsyntaxhighlight>
 
If expression has value K the above will jump to label labK, if expression is not an integer, or if it outside range from 1 to N, then control passes to label elselab. The else part may be omitted (then out of range values of expression cause an exception).
Line 945 ⟶ 2,054:
it is just:
 
<syntaxhighlight lang ="pop11">return;</langsyntaxhighlight>
 
but it is also possible to specify one or more return values:
 
<langsyntaxhighlight lang="pop11">return(val1, val2, val3);</langsyntaxhighlight>
 
===chain===
Line 955 ⟶ 2,064:
chain has effect of "tail call" but is not necessarily in tail position. More precisely inside proc1.
 
<langsyntaxhighlight lang="pop11">chain proc2(x1, x2, x3);</langsyntaxhighlight>
 
finishes execution of proc1 and transfers control to the proc2 passing it x1, x2, and x3 as arguments. On return from proc2 control passes to caller of proc1.
 
Remark: Pop11 does not perform "tail call optimization", one has to explicitly use chain.
 
=={{header|PureBasic}}==
===Goto===
Transfers control to the label referenced. It is not a safe way to exit loops.
<langsyntaxhighlight PureBasiclang="purebasic">If OpenConsole()
top:
i = i + 1
Line 974 ⟶ 2,084:
Input()
CloseConsole()
EndIf </langsyntaxhighlight>
===Gosub & Return===
Gosub stands for 'Go to sub routine'. A label must be specified after Gosub where the program execution continues and will do so until encountering a Return. When a return is reached, the program execution is then transferred immediately below the Gosub.
Gosub is useful when building fast structured code with very low overhead.
<langsyntaxhighlight PureBasiclang="purebasic">X=1: Y=2
Gosub Calc
;X will now equal 7
Line 985 ⟶ 2,095:
Calc:
X+3*Y
Return ; Returns to the point in the code where the Gosub jumped from</langsyntaxhighlight>
===FakeReturn===
If the command Goto is used within the body of a sub routine, FakeReturn must be used to correct the stack or the program will crash.
<langsyntaxhighlight PureBasiclang="purebasic">Gosub MySub
 
Lable2:
Line 999 ⟶ 2,109:
Goto Lable2
EndIf
Return</langsyntaxhighlight>
 
===OnErrorGoto===
This will transferee the program execution to the defined label if an error accrue.
<langsyntaxhighlight PureBasiclang="purebasic">OnErrorGoto(?MyExitHandler)
 
X=1: Y=0
Line 1,013 ⟶ 2,123:
MyExitHandler:
MessageRequester("Error", ErrorMessage())
End</langsyntaxhighlight>
===OnErrorCall===
Similar to OnErrorGoto() but procedural instead.
<langsyntaxhighlight PureBasiclang="purebasic">Procedure MyErrorHandler()
;All open files etc can be closed here
MessageRequester("Error", ErrorMessage())
Line 1,025 ⟶ 2,135:
X=1: Y=0
Z= X/Y
;This line should never be reached</langsyntaxhighlight>
 
=={{header|Python}}==
===Loops===
Python supports ''break'' and ''continue'' to exit from a loop early or short circuit the rest of a loop's body and "continue" on to the next loop iteration.
<langsyntaxhighlight lang="python"># Search for an odd factor of a using brute force:
for i in range(n):
if (n%2) == 0:
Line 1,039 ⟶ 2,149:
else:
result = None
print "No odd factors found"</langsyntaxhighlight>
In addition, as shown in the foregoing example, Python loops support an ''else:'' suite which can be used to handle cases when the loop was intended to search for something, where the code would break out of the loop upon finding its target. In that situation the ''else:'' suite can be used to handle the failure. (In most other languages one is forced to use a "sentinel value" or a special flag variable ... typically set to "False" before the loop and conditionally set to "True" within the loop to handle situations for which the Python ''else:'' on loops is intended).
 
Line 1,052 ⟶ 2,162:
A custom Exception class is normally declared with the ''pass'' statement as no methods of the parent class are over-ridden, no additional functionality is defined and no attributes need be set. Example:
 
<syntaxhighlight lang ="python">class MyException(Exception): pass</langsyntaxhighlight>
 
One normally would choose the most similar existing class. For example if MyException was going to be raised for some situation involving an invalid value it might be better to make it a subclass of ValueError; if it was somehow related to issues with inappropriate objects being passed around then one might make it a subclass of TypeError.
Line 1,060 ⟶ 2,170:
To create a "virtual base class" (one which is not intended to be directly instantiated, but exists solely to provide an inheritance to it's derived classes) one normally defines the requisite methods to raise "NotImplementedError" like so:
 
<langsyntaxhighlight lang="python">class MyVirtual(object):
def __init__(self):
raise NotImplementedError</langsyntaxhighlight>
 
It then becomes necessary for any descendants of this class to over-ride the ''__init__()'' method. Any attempt to instantiate a "MyVirtual" object directly will raise an exception.
Line 1,068 ⟶ 2,178:
 
'''Case 1 - Try, Except'''
<langsyntaxhighlight lang="python">try:
temp = 0/0
# 'except' catches any errors that may have been raised between the code of 'try' and 'except'
except: # Note: catch all handler ... NOT RECOMMENDED
print "An error occurred."
# Output : "An error occurred"</langsyntaxhighlight>
 
'''Case 2 - Try, Except'''
<langsyntaxhighlight lang="python">try:
temp = 0/0
# here, 'except' catches a specific type of error raised within the try block.
except ZeroDivisionError:
print "You've divided by zero!"
# Output : "You've divided by zero!"</langsyntaxhighlight>
 
'''Case 3 - Try, Except, Finally'''
<langsyntaxhighlight lang="python">try:
temp = 0/0
except:
Line 1,094 ⟶ 2,204:
# Output :
# An error occurred
# End of 'try' block...</langsyntaxhighlight>
 
Note: Prior to version 2.5 a ''try:'' statement could contain either series of ''except:'' clauses '''or''' a ''finally:'' clause but '''not both.''' It was thus necessary to nest the exception handling in an enclosing ''try:''...''finally:'' loop like so:
It was thus necessary to nest the exception handling in an enclosing ''try:''...''finally:'' loop like so:
 
<langsyntaxhighlight lang="python">try:
try:
pass
Line 1,105 ⟶ 2,216:
except SomeOtherException:
finally:
do_some_cleanup() # run in any case, whether any exceptions were thrown or not</langsyntaxhighlight>
 
'''Case 4 - Try, Except, Else'''
<langsyntaxhighlight lang="python">try:
temp = 1/1 # not a division by zero error
except ZeroDivisionError: # so... it is not caught
Line 1,116 ⟶ 2,227:
print "No apparent error occurred."
# Output :
# No apparent error occurred.</langsyntaxhighlight>
 
'''Case 5 - Try, Except, break, continue'''
<langsyntaxhighlight lang="python">i = 0
while 1: # infinite loop
try:
Line 1,138 ⟶ 2,249:
# Output :
# You've divided by zero. Decrementing i and continuing...
# Imaginary Number! Breaking out of loop</langsyntaxhighlight>
 
'''Case 6 - Creating your own custom exceptions, raise'''
<langsyntaxhighlight lang="python"># Let's call our custom error "StupidError"; it inherits from the Exception class
 
class StupidError(Exception): pass
Line 1,153 ⟶ 2,264:
 
# Output :
# Something stupid occurred: Segfault</langsyntaxhighlight>
 
===continue, else in "for" loop===
<langsyntaxhighlight lang="python"> i = 101
for i in range(4): # loop 4 times
print "I will always be seen."
Line 1,175 ⟶ 2,286:
if(__name__ == "__main__"):
main()</langsyntaxhighlight>
 
===The "with" statement===
Line 1,181 ⟶ 2,292:
See [[http://www.python.org/peps/pep-0343.html PEP 0343, The "with" statement]]
 
<langsyntaxhighlight lang="python">class Quitting(Exception): pass
max = 10
with open("some_file") as myfile:
Line 1,189 ⟶ 2,300:
if exit_counter > max:
raise Quitting
print line,</langsyntaxhighlight>
 
The ''with'' statement allows classes to encapsulate "final" (clean-up) code which will automatically be executed regardless of exceptions that occur when working "with" these objects. Thus, for the foregoing example, the file will be closed regardless of whether it's more than 10 lines long. Many built-in and standard library classes have "context managers" which facilitate their use in ''with:'' code. In addition it's possible to define special __enter__() and __exit__() methods in one's own classes which will be implicitly called by the interpreter when an object is used within a ''with:'' statement.
Line 1,205 ⟶ 2,316:
1
 
=={{header|Quackery}}==
 
A Quackery program is a dynamic array ('''''nest''''') of numbers (bigints) operators (opcodes or primitives) and nests (named or explicit). It is evaluated by a depth first traversal of the structure, placing numbers on a data stack, and keeping track of the evaluation with a return stack. Flow control is achieved with meta-control flow operators, which modify the return stack during evaluation. The naming convention for meta-control flow operators is to wrap them in reversed brackets. They are <code>]again[ ]done[ ]if[ ]iff[ ]else[ ]'[ ]do[ ]this[</code> and <code>]bailby[</code>.
 
The first five, <code>]done[ ]again[ ]if[ ]iff[ ]else[</code>, are used to create a mix and match set of control flow words.
 
<pre>
[ ]again[ ] is again
[ ]done[ ] is done
[ ]if[ ] is if
[ ]iff[ ] is iff
[ ]else[ ] is else</pre>
 
<code>again</code> causes evaluation of the current nest to start again.
 
<code>done</code> causes evaluation of the current nest to end, and evaluation of the calling nest to continue.
 
<code>if</code> conditionally skips over the next item in the nest being evaluated. (dependant on the top of the data stack; it skips if the TOS is zero, and does not skip if it is a non-zero number. If it is not a number evaluation halts and a problem is reported.
 
<code>iff</code> is like <code>if</code> but conditionally skips over the next two items. It combines with <code>else</code> (below) to form an if...else... construct, and with other words to form more control flow structures (below).
 
<code>else</code> unconditionally skips over the next item in the nest being evaluated.
 
Also provided are <code>until</code> and <code>while</code>, and the programmer can add more as desired.
 
<pre>[ not if ]again[ ] is until
[ not if ]done[ ] is while</pre>
 
As this is a mix and match word set, complex control-flow structures can be made, restricted only to single-point of entry, achieved by the intentional omission of a <code>go-to</code> operator. For example, this code fragment from the task [[Largest number divisible by its digits#Quackery|Largest number divisible by its digits]].
<pre> [ 504 -
dup digits
dup 5 has iff
drop again
dup 0 has iff
drop again
repeats if again ]</pre>
 
<code>' do this</code>enable first and higher order functions, and recursion. They are defined using meta control flow operators.
<pre>
[ ]'[ ] is '
[ ]do[ ] is do
[ ]this[ ] is this</pre>
 
<code>'</code> unconditionally skips over the next item in the current nest, and places (a pointer to) it on the data stack.
 
<code>do</code> evaluates the item on the top of the data stack.
 
<code>this</code> places (a pointer to) the nest currently being evaluated on the data stack. so, for example, the phrase <code>this do</code> will cause the nest containing the phrase to be evaluated recursively. For convenience, the word <code>recurse</code> is provided which does the same thing.
 
<pre>[ ]this[ do ] is recurse</pre>
 
For more complex recursive situations the words <code>this</code> and <code>do</code> can be deployed at different levels of nesting, and additionally a forward referencing mechanism is provided. This example is from the task [[Mutual recursion#Quackery|Mutual recursion]].
<pre> forward is f ( n --> n )
 
[ dup 0 = if done
dup 1 - recurse f - ] is m ( n --> n )
[ dup 0 = iff 1+ done
dup 1 - recurse m - ]
resolves f ( n --> n )</pre>
 
<code>]'[</code> and <code>do</code> are also used to create the iterative looping word <code>times</code>, which will repeat the next item in the nest a specified number of times. The index of the loop is available from the word <code>i^</code>, which counts up from zero with each iteration, and the word <code>i</code>, which counts down to zero. The index can be modified with the words <code>step</code>, which causes the index to be incremented by a specified number, <code>refresh</code>, which resets it to the originally specified number of iterations, and <code>conclude</code>, which will sets it to zero.
 
<code>times</code> is used in the definition of <code>witheach</code>, which iterates over a nest placing the next item in the nest on the data stack with each iteration, so <code>I^ I step refresh conclude</code> are available within <code>witheach</code> loops.
<pre> ' [ 10 11 12 13 14 15 16 17 18 19 ]
witheach
[ dup 14 > iff
[ drop conclude ] done
echo
say " is item number " i^ echo cr
2 step ]</pre>
{{out}}
 
<pre>10 is item number 0
12 is item number 2
14 is item number 4</pre>
 
<code>witheach</code> can be used to define [[Higher-order functions#Quackery|Higher-order functions]].
 
<code>]bail-by[</code> removes a specified number of returns from the return stack. This is a high risk activity, as the data stack and ancillary stacks used by <code>times</code> and others are not restored in the process, additionally many words add items to the return stack that need to be accounted for. Without proper precautions it is an effective way of causing unpredictable behaviour (usually crashing). It exists primarily for the backtracking provided by the words <code>backup</code>, <code>bail</code>, and <code>bailed</code>, which do take the proper precautions.
 
=={{header|Racket}}==
=== exit ===
Racket's <tt>exit</tt> quits the whole process, optionally returning an exit code. Note that there is an <tt>exit-handler</tt> that can be set to intercept such exit attempts.
 
=== goto ===
Racket doesn't have a <tt>goto</tt>, but like other implementations of Scheme, it adopts the mantra of "Lambda: the Ultimate GOTO" by having all tail calls optimized. This allows writing code that is no different from your average assembly code -- for example, here's a direct translation of [[Greatest_common_divisor#x86_Assembly]] into a Racket function:
 
<syntaxhighlight lang="racket">
#lang racket
 
;; some silly boilerplate to mimic the assembly code better
(define r0 0)
(define (cmp r1 r2) (set! r0 (sgn (- r1 r2))))
(define (je true-label false-label) (if (zero? r0) (true-label) (false-label)))
(define (goto label) (label))
 
(define (gcd %eax %ecx)
(define %edx 0)
(define (main) (goto loop))
(define (loop) (cmp 0 %ecx)
(je end cont))
(define (cont) (set!-values [%eax %edx] (quotient/remainder %eax %ecx))
(set! %eax %ecx)
(set! %ecx %edx)
(goto loop))
(define (end) (printf "result: ~s\n" %eax)
(return %eax))
(main))
</syntaxhighlight>
 
=== Exceptions ===
 
Racket has exceptions which are used in the usual way, and <tt>with-handlers</tt> to catch them. In fact, any value can be raised, not just exceptions. For example:
 
<syntaxhighlight lang="racket">
(define (list-product l)
(with-handlers ([void identity])
(let loop ([l l] [r 1])
(cond [(null? l) r]
[(zero? (car l)) (raise 0)]
[else (loop (cdr l) (* r (car l)))]))))
</syntaxhighlight>
 
=== Continuations ===
 
Racket has full continuations, of all kinds, including delimited and not. That's plenty of control flow...
 
=== And more ===
 
Given that Racket has macros, and continuations, and a zillion other features, it is easy to implement
new control flow expressions, so any list will not be exhaustive.
 
=={{header|Raku}}==
(formerly Perl 6)
===Control exceptions===
Control flow is extensible in Raku; most abnormal control flow (including the standard loop and switch exits) is managed by throwing control exceptions that are caught by the code implementing the construct in question. Warnings are also handled via control exceptions, and turn into control flow if the dynamic context chooses not to resume after the warning. See [[https://design.raku.org/S04.html#Control_Exceptions S04/Control exceptions]] for more information.
===Phasers===
Phasers are blocks that are transparent to the normal control flow but that are automatically called at an appropriate phase of compilation or execution. The current list of phasers may be found in [[https://design.raku.org/S04.html#Phasers S04/Phasers]].
===goto===
<syntaxhighlight lang="raku" line>TOWN: goto TOWN;</syntaxhighlight>
Labels that have not been defined yet must be enclosed in quotes.
 
=={{header|REBOL}}==
<langsyntaxhighlight REBOLlang="rebol">REBOL [
Title: "Flow Control"
Author: oofoe
Date: 2009-12-05
URL: http://rosettacode.org/wiki/Flow_Control_Structures
]
Line 1,276 ⟶ 2,527:
print div 10 2
print div 10 1
print div 10 0</langsyntaxhighlight>
 
 
=={{header|Relation}}==
 
* '''stop''' ends execution of the entire program
 
=={{header|REXX}}==
===exitbreak===
(See the '''leave''' statement.)
The EXIT statement terminates the running (REXX) program and passes control to
===call===
<br> the invoking program (it could be the shell/host/supervisor program).
The '''call''' statement immediately transfers control to a named subroutine, and the '''call''' statement may have any number (or none) parameters. &nbsp; (However, most REXXes have some practical limit to the number of arguments, usually at least 50).
<br> If the invoking program is a REXX program, it also is terminated.
 
<br>
The named subroutine may or may not return a &nbsp; '''result''' &nbsp; (which is similar to a ''return code'', but REXX allows character strings as well).
<br> If an expression is coded, it normally is used to set the return code (also called
 
<br> return code, completion code, or other such names).
(Also, see '''function invocation''' and '''signal''' statement below.)
<br>
<syntaxhighlight lang="rexx">call routineName /*no arguments passed to routine.*/
<br> Some operating systems require the expression to be a whole number (often with a
call routineName 50 /*one argument (fifty) passed. */
<br> no expression or a [null] expression is usually taken to mean a return code of 0).
call routineName 50,60 /*two arguments passed. */
<lang rexx>
call routineName 50, 60 /*(same as above) */
call routineName 50 ,60 /*(same as above) */
call routineName 10*5 , 8**4 - 4 /*(same as above) */
call routineName 50 , , , 70 /*4 args passed, 2nd&3rd omitted.*/
/*omitted args are NOT null. */
call routineName ,,,,,,,,,,,,,,,,800 /*17 args passed, 16 omitted. */
call date /*looks for DATE internally first*/
call 'DATE' /* " " " BIF | externally*/</syntaxhighlight>
real-life example:
<syntaxhighlight lang="rexx">numeric digits 1000 /*prepare for some gihugeic numbers.*/
...
n=4
call factorial n
say n'!=' result
exit
/*──────────────────────────────────FACTORIAL subroutine────────────────*/
factorial: parse arg x
!=1
do j=2 to x
!=!*j
end /*j*/
return !</syntaxhighlight>
 
===case===
exit expression
(See the '''select''' statement below.)
</lang>
===return===
the RETURN statement terminates the running (REXX) program and passes control to
<br> the invoking program (it could be the shell/host/supervisor program).
<br> If the invoking program isn't a REXX program, the RETURN statement acts like an EXIT.
<br>
<br> If the invoker is a REXX program and the RETURN statement has no EXPRESSION coded, and
<br> the invoker expects a RESULT, a SYNTAX condition (error) is raised --- which usually
<br> results in an abnormal termination of the invoking REXX program (this condition can be
<br> trapped, however).
<lang rexx>
return
 
===exceptions===
return expression
(See the '''signal''' statement and '''raising conditions''' below.)
</lang>
===signal===
The SIGNAL statement can be thought of as a GO TO statement, however, on issuance of
<br> a SIGNAL statement, all executing DO loops and SELECTs are terminated.
<br> Essentially, that means that there is no real way to re-enter a DO loop once a SIGNAL
<br> statement is used.
<br>
<br> Once a SIGNAL statement is executed, control passed to the first occurance of the label
<br> specified (more than one label with the same name isn't considered an error).
<br> The label can be any combination of letters, digits, periods, and some special symbols,
<br> the most common are $, #, @, !, ?, and _ (underscore or underbar).
<br> Some versions of REXX (CMS, TSO, R4) also allow the cent sign (¢).
<br>
<br> The SIGNAL statement is also used to transfer control in case of some specific conditions:
<br>
<br> ∙ when an I/O stream (could be a file) isn't ready.
<br> ∙ when the REXX program used a variable that isn't defined.
<br> ∙ when a REXX syntax error occurs.
<br> ∙ when the program is HALTed (usually via a Ctrl─Alt─Del ──or── PA1 ──or── somesuch.
<br> ∙ when there is a loss of digits.
<br> ∙ when a command executed returns an error return code [other than 0 (zero)].
<br> ∙ when a command executed indicates a failure.
<lang rexx>
signal on error
signal on failure
signal on halt
signal on lostdigits
signal on notready
signal on novalue
signal on syntax
 
===exit===
The '''exit''' statement terminates the running (REXX) program and passes control to the invoking program (it could be the shell/host/supervisor program).
 
If an expression is coded, it normally is used to set the '''result''' (if a REXX program) or return code (also called ''RetCode'', ''RC'', ''completion code'', or other such names).
signal off error
signal off failure
signal off halt
signal off lostdigits
signal off notready
signal off novalue
signal off syntax
 
When using the '''exit''' with an expressing to pass control to the operating system (i.e., exiting a REXX program), some operating systems require the expression to be a whole number within a certain range (often with a no expression or a [null] expression, which is usually taken to mean a return code of '''0''').
signal on novalue
x=oopsay+1
novalue: say
say '*** error! ***'
say
say 'undefined REXX variable' condition("D")
say
say 'in line' sigl
say
say 'REXX source statement is:'
say sourceline(sigl)
say
exit 13
</lang>
 
If the expression is a number, it is normalized to the current '''numeric digits'''.
===leave===
The LEAVE statement transfer control to the next REXX statement following the END
<br> statment of the current DO loop.
<br> The LEAVE statement can also specify which DO loop is to be left if the DO loop has
<br> a named variable.
<lang rexx>
do j=1 to 10
say 'j=' j
if j>5 then leave
say 'negative j=' -j
end
say 'end of the DO loop for j.'
ouch=60
sum=0
 
(Also, see the '''return''' statement below.)
do k=0 to 100 by 3
<syntaxhighlight lang="rexx">exit
say 'k=' k
 
exit expression</syntaxhighlight>
do m=1 to k
 
if m=ouch then leave k
===function invocation===
sum=sum+m
A function invocation (similar to a '''call''') immediately transfers control to a named function (subroutine), and the function/subroutine invocation statement may have any number (or none) parameters. &nbsp; (However, most REXXes have some practical limit to the number of arguments, usually at least 50).
end
 
(In REXX, the only difference between a ''function'' and a ''subroutine'' is that a ''function'' returns a &nbsp; '''result''' &nbsp; --- that is, some value is returned, which may be ''null'')
 
The named function/subroutine must return a &nbsp; '''result''' &nbsp; (which is similar to a return code, but REXX allows character strings as well).
 
If no &nbsp; '''result''' &nbsp; is returned, REXX generates a syntax error &nbsp; (which may be trapped via the '''signal on syntax''' instruction).
 
(Also, see the '''call''' statement above.)
<syntaxhighlight lang="rexx">numeric digits 1000 /*prepare for some gihugeic numbers.*/
...
n=4
say n'!=' factorial(n)
exit
/*──────────────────────────────────FACTORIAL subroutine────────────────*/
factorial: parse arg x
!=1
do j=2 to x
!=!*j
end /*j*/
return !</syntaxhighlight>
 
end
say 'sum=' sum
</lang>
===iterate===
The '''iterate''' statement immediately transfer control to the innermost active &nbsp; '''do''' &nbsp; statement in which the '''iterate''' statement is located, that is, it (may) iterates (increments or decrements) the named REXX variable (if any) that is specified on the &nbsp; '''do''' &nbsp; statement. &nbsp; The '''iterate''' statement can also specify which &nbsp; '''do''' &nbsp; loop is to be iterated if there is a named variable on the '''do''' loop.
The ITERATE statement immediately transfer control to the DO statement, that is, it iterates
<br> (increments or decements) the named REXX variable that is specified on the DO statement.
<br> The ITERATE statement can also specify which DO loop is to be iterated.
<lang rexx>
sum=0
 
(All indentations in REXX are merely cosmetic and are used for readability.}
do j=1 to 1000
<syntaxhighlight lang="rexx">sum=0
if j//3==0 | j//7==0 then iterate
do j=1 to 1000
sum=sum+j
if j//3==0 | j//7==0 then iterate
end
sum=sum+j
end /*j*/
 
/*shows sum of 1k numbers except those divisible by 3 or 7.*/
say 'sum='sum
...
numeric digits 5000
prod=0
do k=1 to 2000
do m=1 to k
if m>99 then iterate k
prod=prod*m
end /*m*/
end /*k*/
say 'prod=' prod</syntaxhighlight>
 
do k=1==go to 2000===
(See the '''signal''' statement.)
 
===leave===
do m=1 to k
The '''leave''' statement transfer control to the next REXX statement following the &nbsp; '''end''' &nbsp; statement of the current (active) &nbsp; '''do''' &nbsp; loop in which the '''leave''' statement is located. &nbsp; The '''leave''' statement can also specify which '''do''' loop is to be left (terminated) if the '''do''' loop has a named variable.
if m>99 then iterate k
<syntaxhighlight lang="rexx"> do j=1 to 10
prod=prod*m
say 'j=' endj
if j>5 then leave
say 'negative j=' (-j)
end /*j*/
 
say 'end of the DO loop for j.'
end
 
say 'prod=' prod
ouch=60
</lang>
sum=0
===call===
do k=0 to 100 by 3
The CALL statement immediately transfer control to a named subroutine, and the CALL
say 'k=' k
<br> statement may have any number (or none) parameters.
do m=1 to k
<br> The named subroutine may or may not return a RESULT (which is similar to a return code).
if m=ouch then leave k
<lang rexx>
numeric digits 1000 /*prepare for some gihugeic numbers.*/ sum=sum+m
end /*m*/
end /*k*/
say 'sum=' sum</syntaxhighlight>
 
n=4
===raising conditions===
call factorial n
 
say n'!=' result
(REXX) conditions can be raised by causing some kind of "failure" or triggering event &nbsp; (such as division by zero).
 
A '''signal''' statement must have been issued previous to the event being triggered to enable trapping.
 
It should be noted that some older REXXes don't support all the '''signal''' variants.
 
(Also, see the '''signal''' statement below.)
<syntaxhighlight lang="rexx">...
signal on syntax
...
y=4 - 4
x=66
say x/y /*divide x by y.*/
say "yup, that's a divide by zero, by gum."
exit
 
syntax: say
 
/* We can now possibly do some repair work , but most people trap */
factorial: parse arg x
/* the condition, display where it happened, the REXX sourceline */
!=1
/* (the actual REXX statement), which condition was triggered, */
/* display any other pertinent REXX variables, which line in the */
/* REXX program, and then (usually) exit with some kind of error */
/* message and error code indicator. */
/* Note: the "name" of the REXX program isn't quite accurate, */
/* rather, it is the name that was invoked (called by), which may */
/* be different name than the actual program being executed. */
 
say '──────────────────────error!─────────────────────────'
do j=2 to x
say 'that division (above) will cause control to get here.'
!=!*j
parse source . . fid .
end
say; say 'REXX raised a SYNTAX error in program:' fid
say; say 'it occurred on line' sigl
say; say 'the REXX statement is:' /*put it on separate line.*/
say sourceline(sigl)
say; say 'which code:' condition('C') "error"
say; say 'error code:' condition('D')
say; say "Moral: don't do that."
exit 13</syntaxhighlight>
{{out}}
<pre>
──────────────────────error!─────────────────────────
that division (above) will cause control to get here.
 
REXX raised a SYNTAX error in program: D:\OOPSsay.REX
 
it occurred on line 6
 
the REXX statement is:
say x/y /*divide x by y.*/
 
which code: SYNTAX error
 
error code: Error 42.3: Arithmetic overflow; divisor must not be zero
 
Moral: don't do that.
</pre>
A note regarding the following REXXes:
::* PC/REXX
::* Personal REXX
::* R4
::* ROO
::* CMS REXX
::* TSO REXX
::* ooRexx
::* Regina REXX
Three conditions allow to specify CALL ON condition: ERROR, FAILURE, and HALT (there may be others).
 
From the corresponding condition handlers one can RETURN to the instruction
following the instruction/command where the condition was encountered.
<br>A short example:
<syntaxhighlight lang="rexx">Say 'Interrupt this program after a short while'
Call on halt
Do i=1 To 10000000
j=i**2+1
End
halt: Say i j
Return</syntaxhighlight>
 
===return===
The '''return''' statement terminates the running (REXX) program (which could be a subroutine or function) and passes control to the invoking program (it could be the shell/host/supervisor program).
 
If no internal subroutine or function is active, &nbsp; '''return''' &nbsp; is equivalent to &nbsp; '''exit'''.
 
If a subroutine is active (a '''call''' was used), control goes to the instruction after the '''call''' statement.
 
If a function is active (a function reference was used) control goes back to the expression evaluation using the value resulting from the &nbsp; '''return''' &nbsp; expression.
 
(Also, see the '''exit''' statement above.)
<syntaxhighlight lang="rexx">return
 
return expression</syntaxhighlight>
 
return !
</lang>
===select===
The SELECT'''select''' statement is used to conditionalyconditionally test for cases to selectively execute REXX statement(s).
<syntaxhighlight lang="rexx">...
<br> statement(s).
<lang rexx>
prod=1
a=7 /*or somesuch.*/
Line 1,469 ⟶ 2,762:
 
op='**' /*or whatever.*/
...
select
when op=='+' then r=a+b /*add. */
when op=='-' then r=a-b /*subtract. */
when op=='∙' then do; r=a*b; prod=prod*r; end /*multiply.*/
when op=='*' then r=a*b /*multiply. */
when op=='**' then r=a**b /*power (exponentiation) */
when op=='/' & b\=0 then r=a/b /*divide. */
when op=='%' & b\=0 then r=a/b /*interger divide. */
when op=='//' & b\=0 then r=a/b /*modulus (remainder). */
when op=='||' then r=a||b /*concatenation. */
when op=='caw' then r=xyz(a,b) /*call the XYZ subroutine*/
otherwise r='[n/a]' /*signify not applicable.*/
end /*select*/
 
say 'result for' a op b "=" r</syntaxhighlight>
select
when op=='+' then r=a+b /*add. */
when op=='-' then r=a-b /*subtract. */
when op=='*' then do; r=a*b; prod=prod*r; end /*multiply.*/
when op=='*' then r=a*b /*multiply. */
when op=='/' & b\=0 then r=a/b /*divide. */
when op=='%' & b\=0 then r=a/b /*interger divide. */
when op=='//' & b\=0 then r=a/b /*modulus (remainder). */
when op=='||' then r=a||b /*concatenation. */
when op=='caw' then r=xyz(a,b) /*call the XYZ subroutine*/
otherwise r='[n/a]' /*signify not applicable.*/
end
 
===signal===
say 'result for' a op b "=" r
The '''signal''' statement can be thought of as a ''GO TO'' or ''JUMP'' statement, however, on issuance of a '''signal''' statement, all active '''do''' loops and '''select''' structures are terminated. &nbsp; Essentially, that means that there is no real way to re-enter a '''do''' loop (or a '''select''' structure) once a '''signal''' statement is used.
</lang>
 
Once a '''signal''' statement is executed (or invoked), control passed to the first occurrence of the label specified (in REXX, more than one label with the same name isn't considered an error). &nbsp; The label can be any combination of letters, digits, periods, and some special symbols, the most common are '''$''', '''#''', '''@''', '''!''', '''?''', and '''_''' (underscore or underbar). &nbsp; Some versions of REXX (CMS, PC/REXX, Personal REXX, TSO, R4, ROO) also allow the cent sign ('''¢'''), some of those REXXes support the British pound (currency) symbol ('''£''').
 
The '''signal''' statement is also used to transfer control in case of some specific conditions:
::* when an I/O stream (could be a file) isn't ready.
::* when the REXX program used a variable that isn't defined.
::* when a REXX syntax error occurs.
::* when the program is '''halt'''ed (this depends on the operating system):
::::* Ctrl-Alt-Del &nbsp; &nbsp; under VM/CMS or MVS/TSO (generic names)
::::* HX &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; under VM/CMS or MVS/TSO (generic names)
::::* PA1 &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; under VM/CMS or MVS/TSO (generic names)
::::* Ctrl-c &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; some Unix, BSD variants
::::* Del &nbsp; (key) &nbsp; &nbsp; most System V variants
::::* SIGINT &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; (SIGnal INTerrupt) some variants of UNIX
::::* kill(1) &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; from the command line (same as above)
::::* signal(3) &nbsp; &nbsp; &nbsp; &nbsp; from a program (same as above)
::::* &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [to be sure, check with your operating system documentation]
::* when there is a loss of decimal digits &nbsp; (for the newer REXXes).
::* when a command executed returns an error return code [other than 0 (zero)].
::* when a command executed indicates a failure.
It should be noted that some older REXXes don't support all the '''signal''' variants.
 
(Also, see '''raising conditions''' above.)
<syntaxhighlight lang="rexx">...
signal on error
signal on failure
signal on halt
signal on lostdigits /*newer REXXes.*/
signal on notready
signal on novalue
signal on syntax
 
signal off error
signal off failure
signal off halt
signal off lostdigits /*newer REXXes.*/
signal off notready
signal off novalue
signal off syntax
...
signal on novalue
...
x=oopsay+1 /* ◄─── this is it.*/
exit
 
novalue: say
say '───────────────────────────error!─────────────────────────────────'
say 'that reference to oopsay (above) will cause control to get here.'
parse source . . fid .
say; say 'REXX raised a NOVALUE error in program:' fid
say; say 'it occurred on line' sigl
say; say 'the REXX statement is:' /*put it on separate line.*/
say sourceline(sigl)
say; say 'which code:' condition('C') "error"
say; say 'REXX variable:' condition('D')
say; say "Moral: shouldn't do that."
</syntaxhighlight>
{{out}}
<pre>
───────────────────────────error!─────────────────────────────────
that reference to oopsay (above) will cause control to get here.
 
REXX raised a NOVALUE error in program: D:\flow_sig.rex
 
it occurred on line 20
 
the REXX statement is:
x=oopsay+1 /* ◄─── this is it.*/
 
which code: NOVALUE error
 
REXX variable: OOPSAY
 
Moral: shouldn't do that.
</pre>
 
=={{header|Ring}}==
<syntaxhighlight lang="ring">
i = 1
while true
see i + nl
if i = 10 see "Break!" exit ok
i = i + 1
end
</syntaxhighlight>
 
=={{header|Ruby}}==
Line 1,497 ⟶ 2,875:
=== exceptions ===
Use <code>raise</code> to throw an exception. You catch exceptions in the <code>rescue</code> clause of a <code>begin...end</code> block.
<langsyntaxhighlight lang="ruby">begin
# some code that may raise an exception
rescue ExceptionClassA => a
Line 1,509 ⟶ 2,887:
ensure
# execute this code always
end</langsyntaxhighlight>
There is also a rescue modifier (example from the [http://www.pragprog.com/titles/ruby/programming-ruby Pickaxe book]):
<langsyntaxhighlight lang="ruby">values = ["1", "2.3", /pattern/]
result = values.map {|v| Integer(v) rescue Float(v) rescue String(v)}
# => [1, 2.3, "(?-mix:pattern)"]</langsyntaxhighlight>
 
=== catch and throw ===
<code>break</code> will only break out of a single level of loop. You can surround code in a catch block, and within the block you can throw a string or symbol to jump out to the end of the catch block (Ruby's GOTO, I suppose):
<langsyntaxhighlight lang="ruby">def some_method
# ...
if some_condition
Line 1,532 ⟶ 2,911:
end
 
puts "continuing after catching the throw"</langsyntaxhighlight>
=== yield ===
<code>yield</code> passes control from the currently executing method to its code block.
 
=={{header|SAS}}==
<langsyntaxhighlight lang="sas">/* GOTO: as in other languages
STOP: to stop current data step */
data _null_;
Line 1,577 ⟶ 2,956:
8 44
;
run;</langsyntaxhighlight>
 
=={{header|TclScala}}==
{{libheader|Scala}}
<syntaxhighlight lang="scala">import Goto._
import scala.util.continuations._
 
object Goto {
 
case class Label(k: Label => Unit)
 
private case class GotoThunk(label: Label) extends Throwable
 
def label: Label @suspendable =
shift((k: Label => Unit) => executeFrom(Label(k)))
 
def goto(l: Label): Nothing =
throw new GotoThunk(l)
 
private def executeFrom(label: Label): Unit = {
val nextLabel = try {
label.k(label)
None
} catch {
case g: GotoThunk => Some(g.label)
}
if (nextLabel.isDefined) executeFrom(nextLabel.get)
}
 
}</syntaxhighlight>
 
=={{header|Sidef}}==
===goto===
<syntaxhighlight lang="ruby">say "Hello"
goto :world
say "Never printed"
@:world
say "World"</syntaxhighlight>
{{out}}
<pre>
Hello
World
</pre>
 
=={{header|SSEM}}==
=== Indirect absolute jump ===
The <tt>000 n to CI</tt> instruction loads the value stored at address <i>n</i> into the Current Instruction register. For instance,
<syntaxhighlight lang="ssem">00101000000000000000000000000000 20 to CI
...
01010000000000000000000000000000 20. 10</syntaxhighlight>
loads the number 10 into CI. Since CI is incremented <i>after</i> the instruction has been executed, rather than before, this fragment will cause execution to jump to address 11.
 
=== Indirect relative jump ===
<tt>100 Add n to CI</tt> increases the number in the CI register by the value stored at address <i>n</i>.
<syntaxhighlight lang="ssem">00101000000001000000000000000000 Add 20 to CI
...
01010000000000000000000000000000 20. 10</syntaxhighlight>
adds 10 to CI. Once again, CI is incremented <i>after</i> the instruction has been executed: so the machine actually jumps ahead by 11 instructions.
 
=={{header|Stata}}==
 
Mata has a '''[https://www.stata.com/help.cgi?m2_goto goto]''' statement. It may be used to break nested loops, or to convert easily Fortran code to Mata.
 
As an example, let's find a Pythagorean triple a,b,c such that a+b+c=n, where n is given. Here goto is used to break the two loops when such a triple is found. A '''[https://www.stata.com/help.cgi?m2_return return]''' can be used in such situations, unless one has to do further computations after the loop.
 
<syntaxhighlight lang="stata">mata
function pythagorean_triple(n) {
for (a=1; a<=n; a++) {
for (b=a; b<=n-a; b++) {
c=n-a-b
if (c>b & c*c==a*a+b*b) {
printf("%f %f %f\n",a,b,c)
goto END
}
}
}
END:
}
 
pythagorean_triple(1980)
165 900 915</syntaxhighlight>
 
=={{header|Tcl}}==
=== after ===
 
The <tt>after</tt> facility can be used to execute some code at some future time asynchronously, like this
at some future time asynchronously, like this
 
<syntaxhighlight lang ="tcl">after 1000 {myroutine x}</langsyntaxhighlight>
 
which will call "<tt>myroutine</tt>" with parameter "<tt>x</tt>" 1000ms from 'now'; no matter what other code might be running at the time (i.e. "<tt>after</tt>"; schedules the execution, then returns and continues program flow with the following code).
no matter what other code might be running at the time (i.e. "<tt>after</tt>"; schedules the execution, then returns and continues program flow with the following code).
 
The scheduled task can be removed from the scheduler for example with
 
<syntaxhighlight lang ="tcl">after cancel myroutine</langsyntaxhighlight>
 
(other ways are possible).
 
The correct way to schedule some regularly recurring task in TCL is to incorporate a self-scheduling at the end of the routine. For example the following will produce a clock whose display is updated once a second:
is to incorporate a self-scheduling at the end of the routine.
For example the following will produce a clock
whose display is updated once a second:
 
<langsyntaxhighlight lang="tcl">package require Tk
proc update {} {
.clockface configure -text [clock format [clock seconds]]
Line 1,604 ⟶ 3,067:
# now just create the 'clockface' and call ;update' once:
pack [label .clockface]
update</langsyntaxhighlight>
 
=== loop control ===
Line 1,611 ⟶ 3,074:
=== exception ===
Tcl's <code>catch</code> command can be used to provide a basic exception-handling mechanism:
<langsyntaxhighlight lang="tcl">if {[catch { ''... code that might give error ...'' } result]} {
puts "Error was $result"
} else {
''... process $result ...''
}</langsyntaxhighlight>
Tcl 8.6 also has a <tt>try</tt>…<tt>trap</tt>…<tt>finally</tt> structure for more complex exception handling.
<langsyntaxhighlight lang="tcl">try {
# Just a silly example...
set f [open $filename]
Line 1,626 ⟶ 3,089:
} finally {
close $f
}</langsyntaxhighlight>
 
=== custom control structures ===
A novel aspect of Tcl is that it's relatively easy to create new control structures (more detail at http://wiki.tcl.tk/685).
For example, this example defines a command to perform some operation for each line of an input file:
<langsyntaxhighlight lang="tcl">proc forfilelines {linevar filename code} {
upvar $linevar line ; # connect local variable line to caller's variable
set filechan [open $filename]
Line 1,638 ⟶ 3,101:
}
close $filechan
}</langsyntaxhighlight>
Now we can use it to print the length of each line of file "mydata.txt":
<langsyntaxhighlight lang="tcl">forfilelines myline mydata.txt {
puts [string length $myline]
}</langsyntaxhighlight>
 
=={{header|Tiny BASIC}}==
<syntaxhighlight lang="tinybasic"> REM TinyBASIC has only two control flow structures: goto and gosub
LET N = 0
10 LET N = N + 1
PRINT N
IF N < 10 THEN GOTO 10
LET R = 10
15 IF N < 10000 THEN GOSUB 20
IF N > 10000 THEN GOTO 30
GOTO R + 5 REM goto can be computed
20 LET N = N * 2
PRINT N
RETURN REM gosub returns to where it was called from
REM meaning it can be called from multiple
REM places in the program
30 LET N = 0
40 GOSUB 105-N REM gosub can be computed as well
IF N <= 5 THEN GOTO 40
END
100 PRINT "ZERO"
101 PRINT "1"
102 PRINT "22"
103 PRINT "333"
104 PRINT "4444"
105 PRINT "55555"
LET N = N + 1
RETURN REM one return can serve several gosubs</syntaxhighlight>
 
=={{header|Visual Basic .NET}}==
Line 1,650 ⟶ 3,146:
This skips the line that changes the value of x to 5.
 
<langsyntaxhighlight lang="vbnet"> Sub bar2()
Dim x = 0
GoTo label
Line 1,656 ⟶ 3,152:
label:
Console.WriteLine(x)
End Sub</langsyntaxhighlight>
 
=== On Error Goto ===
 
This brancesbranches in the event of an error. Usually there is an Exit (Sub|Function) to seperateseparate the normal code from the error handling code
 
<langsyntaxhighlight lang="vbnet"> Sub foo()
On Error GoTo label
'do something dangerous
Line 1,668 ⟶ 3,164:
label:
Console.WriteLine("Operation Failed")
End Sub</langsyntaxhighlight>
 
''This style of code is rarely used.''
Line 1,676 ⟶ 3,172:
This performs a sequence of actions. If any action fails, the exception is discarded and next operation is performed.
 
<langsyntaxhighlight lang="vbnet">Sub foo2()
On Error Resume Next
Operation1()
Line 1,682 ⟶ 3,178:
Operation3()
Operation4()
End Sub</langsyntaxhighlight>
 
''This style of code is rarely used.''
Line 1,690 ⟶ 3,186:
This shows the classical and modern syntax for exiting a sub routine early.
 
<langsyntaxhighlight lang="vbnet">Sub Foo1()
If Not WorkNeeded() Then Exit Sub
DoWork()
Line 1,698 ⟶ 3,194:
If Not WorkNeeded() Then Return
DoWork()
End Sub</langsyntaxhighlight>
 
=== Return value / Exit Function ===
 
This shows the classical and modern syntax for exiting a function early. There is an implied variable with the same name as the function. This variable is write-only.
There is an implied variable with the same name as the function.
This variable is write-only.
 
<langsyntaxhighlight lang="vbnet">Function Foo3()
Foo3 = CalculateValue()
If Not MoreWorkNeeded() Then Exit Function
Line 1,714 ⟶ 3,212:
If Not MoreWorkNeeded() Then Return result
Return CalculateAnotherValue()
End Function</langsyntaxhighlight>
 
=={{header|Wren}}==
Wren has three control flow statements, '''break''', '''continue''' and '''return'''.
 
'''Break''' exits from the nearest enclosing for or while loop and transfers control to the next statement after that.
 
'''Continue''' (from v0.4.0) jumps to the next iteration of the nearest enclosing for or while loop.
 
'''Return''' exits from a method or function and can be optionally followed by a value. Controls returns to the caller. It can also be used to exit the current module from 'top level' code.
 
Whilst part of the standard library rather than the language itself, the '''Fiber.abort''' method can be used to exit the script when an error occurs. However, it is possible to catch the error using '''Fiber.try'''.
 
'''Fiber.suspend''' pauses the current fiber and stops the interpreter. Control returns to the host application, if there is one. However, execution of the script can be resumed later by storing a reference to the current fiber and then calling that.
 
The following code demonstrates each of the above apart from '''Fiber.suspend''' which simply exits a CLI script.
<syntaxhighlight lang="wren">var func = Fn.new { |n|
var i = 1
while (true) {
if (i == 1) {
i = i + 1
continue // jumps to next iteration
}
System.print(i)
if (i == n) break // exits while loop
i = i + 1
}
if (n < 3) return // exits function
System.print(n + 1)
}
 
var fiber = Fiber.new {
Fiber.abort("Demo error") // error occurred, abort script
}
 
var a = [2, 3]
for (n in a) {
func.call(n)
if (n > 2) return // end module and hence the script as it's a single module script
var error = fiber.try() // catch any error
System.print("Caught error: " + error)
}</syntaxhighlight>
 
{{out}}
<pre>
2
Caught error: Demo error
2
3
4
</pre>
 
=={{header|XPL0}}==
XPL0 does not have a ''goto'' statement, but it has other similar
statements. Its ''quit'' statement jumps out of a ''loop'' block. A
''return'' jumps out of a procedure, or a function where it's also used
to return the numerical result of the function. A ''return'' in the main
procedure terminates a program. An ''exit'' statement terminates a
program from any location. Like the ''return'' statement, it can send an
optional value, in this case to the operating system.
 
Some routines called ''intrinsics'' that are automatically included in a
program also affect flow control. The Abort intrinsic is like the
''exit'' statement except it does not return a value. (It's deprecated in
preference to ''exit''.) The Restart intrinsic, which can be called from
anywhere, restarts a program at its beginning. (The Rerun intrinsic is
used to distinguish a restart from a normal start.) Certain errors such
as divide-by-zero or attempting to open a non-existent file abort a
program. The Trap intrinsic can disable this feature. It's normally used
with the GetErr intrinsic, which provides a way to detect these kinds of
errors and handle them without aborting.
 
=={{header|Yabasic}}==
{{works with|QuickBasic|4.5}}
<syntaxhighlight lang="yabasic">
gosub subrutina
 
label bucle
print "Bucle infinito"
goto bucle
end
 
label subrutina
print "En subrutina"
wait 10
return
end
</syntaxhighlight>
 
=={{header|Z80 Assembly}}==
===JP and JR===
This is the equivalent of <code>GOTO</code> in BASIC, in that after the jump takes place, the CPU has no way of knowing where it came from.
* <code>JP</code> takes three bytes, one for the jump itself, and two for the address. This instruction can jump conditionally based on the status of the zero, carry, sign, and overflow/parity flags. (On Game Boy, there are no sign or overflow/parity flags so those jumps won't work even for <code>JP</code>)
 
* <code>JR</code> is a "short jump" that is program-counter relative. This instruction takes two bytes - one for the jump, and the second is an 8-bit signed offset. The offset represents how many bytes forward or backward to jump - <code>JR</code> can only travel forward 127 bytes and backward 128 bytes, and cannot branch based on the sign or overflow/parity flags - only zero and carry.
 
===Breaking out of a loop===
A subroutine that loops is often escaped with a conditional return, or, if it needs to unwind the stack frame, a conditional jump to an unconditional return.
<syntaxhighlight lang="z80">PrintString:
ld a,(hl) ;HL is our pointer to the string we want to print
cp 0 ;it's better to use OR A to compare A to zero, but for demonstration purposes this is easier to read.
ret z ;return if accumulator = zero
call PrintChar ;prints accumulator's ascii code to screen - on Amstrad CPC for example this label points to memory address &BB5A
inc hl ;next char
jr PrintString ;jump back to the start of the loop. RET Z is our only exit.</syntaxhighlight>
 
In the above example, the stack was never modified (besides the CALL pushing the return address) so <code>RET Z</code> was safe to use. Conditional returns are not safe to use if the stack needs to be unwound prior to exiting, since there's no way to conditionally unwind the stack without conditionally jumping to a section of code that does just that. In which case you don't need the return to be conditional anyway. This contrived example shows this in action.
 
<syntaxhighlight lang="z80">foo:
push af
bar:
ld a,(hl)
cp 255
jr z,exit
inc hl
jr bar
 
exit:
pop af
ret</syntaxhighlight>
 
===DJNZ===
<code>DJNZ</code> stands for "decrement, jump if nonzero." This is the equivalent of x86's <code>LOOP</code> command - as it subtracts 1 from the B register (just B, not BC) and if it's nonzero, jumps to a specified signed 8-bit offset. (It's better to use a label and let the assembler compute the offset for you.) Although this is usually used for looping, it can also jump forward. The same distance limits of <code>JR</code> apply to <code>DJNZ</code> as well. <code>DJNZ</code> cannot be made conditional based on flags, and it doesn't actually change the flags the same way <code>DEC B</code> would.
 
(Game Boy doesn't have this instruction - you'll have to use a combination of <code>DEC B</code> and <code>JR NZ</code>)
 
<syntaxhighlight lang="z80">loop:
;your code goes here
DJNZ loop</syntaxhighlight>
 
===Block Instructions===
These instructions repeat until <code>BC</code> equals zero. They're useful for doing the same thing in a row, but have one-off equivalents that are faster. However, you can often save space by using these, especially if you can't hardcode a fixed repetition count before using one.
 
<code>LDIR</code> is the equivalent of <code>memcpy()</code> in C and <code>rep movsb</code> in x86. It loads from the address stored in HL and stores in the address pointed to by DE, increments both HL and DE, decrements BC, and repeats if BC doesn't equal zero.
 
Essentially it's equivalent to the code below, except in the real <code>LDIR</code> the accumulator isn't actually altered in any way.
<syntaxhighlight lang="z80">_LDIR:
ld a,(hl)
ld (de),a
inc hl
inc de
dec bc
ld a,b
or c ;compare BC to zero
jr nz,_LDIR ;Game Boy doesn't have LDIR so you'll have to use this code instead.</syntaxhighlight>
 
There are several others that work in a similar fashion, such as:
* <code>LDDR</code> - equivalent of x86's <code>REP MOVSB</code> with direction flag set
* <code>CPIR</code> - equivalent of x86's <code>REPNZ SCASB</code> with direction flag clear
* <code>CPDR</code> - equivalent of x86's <code>REPNZ SCASB</code> with direction flag set
* <code>OTIR</code> - equivalent of x86's <code>REP OUTSB</code> with direction flag clear
* <code>OTDR</code> - equivalent of x86's <code>REP OUTSB</code> with direction flag set
* <code>INIR</code> - equivalent of x86's <code>REP INSB</code> with direction flag clear
* <code>INDR</code> - equivalent of x86's <code>REP INSB</code> with direction flag set
 
=={{header|zkl}}==
<syntaxhighlight lang="zkl">continue; continue(n); // continue nth nested loop
break; break(n); // break out of nth nested loop
try{ ... }catch(exception){ ... } [else{ ... }]
onExit(fcn); // run fcn when enclosing function exits</syntaxhighlight>
zkl has state machines for functional style stream processing. There are some special values that machines can return for flow control:
<pre>
Void.Again // call the machine again with next value
Void.Drop // drop an item and call next machine
(Void.Read,n) // read the next n items and pass to the next machine
Void.Skip // ignore this item, ie continue
(Void.Skip,v) // value is v
Void.Stop // stop, ie break
(Void.Stop.v) // value is v
(Void.write,x,y,z) // write x,y,x to sink
</pre>
As an example, decode URL strings:
<syntaxhighlight lang="zkl">urlText.pump(String,
fcn(c){ if(c=="%")return(Void.Read,2); return(Void.Skip,c) },
fcn(_,b,c){(b+c).toInt(16).toChar()})</syntaxhighlight>
has two machines. The second machine only runs if "%" is seen.
<syntaxhighlight lang="zkl">urlText:="http%3A%2F%2Ffoo.com%2Fbar";
urlText.pump(...).println();</syntaxhighlight>
{{out}}<pre>http://foo.com/bar</pre>
5

edits