Jump to content

Flow-control structures: Difference between revisions

→‎{{header|Tcl}}: Add example of 'try' for exception handling
(add E description)
(→‎{{header|Tcl}}: Add example of 'try' for exception handling)
Line 670:
=={{header|Tcl}}==
=== loop control ===
Tcl has the <code>break</code> command to abort the current loop (<tt>for</tt>/<tt>foreach</tt>/<tt>while</tt>) and the <code>continue</code> command to skip to the next loop iteration.
 
=== exception ===
Tcl's <code>catch</code> command can be used to provide a basic exception-handling mechanism:
<lang tcl> if {[catch { ''... code that might give error ...'' } result]} {
puts "Error was $result"
} else {
''... process $result ...''
}</lang>
Tcl 8.6 also has a <tt>try</tt>…<tt>trap</tt>…<tt>finally</tt> structure for more complex exception handling.
 
<lang tcl>try {
# Just a silly example...
set f [open $filename]
expr 1/0
string length [read $f]
} trap {ARITH DIVZERO} {} {
puts "divided by zero"
} finally {
close $f
}</lang>
=== 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).
Eg. defining a command to perform some operation for each line of an input file:
<lang tcl> proc forfilelines {linevar filename code} {
upvar $linevar line ; # connect local variable line to caller's variable
set filechan [open $filename]
Line 690 ⟶ 700:
}
close $filechan
}</lang>
Now use it to print the length of each line of file "mydata.txt":
<lang tcl> forfilelines myline mydata.txt {
puts [string length $myline]
}</lang>
 
=={{header|Visual Basic .NET}}==
Anonymous user
Cookies help us deliver our services. By using our services, you agree to our use of cookies.