Escape is one category of instruction that allows control to dramatically leap from end of a program to another.
The grandfather of all jumps is the goto command that allow programmers to specify the label of the next instruction that should be executed:
start: if (x > 10) goto end // a branch or conditional goto
x = x + 1
println("x = " + x)
goto start // a jump or
unconditional goto
end: println("done")
Once the only way to alter sequence control, the goto is now much discredited for its ability to lead to spaghetti code. It is not included in Java or Scala.
The ability to call procedures and functions and have them return values to the caller enabled programmers to create reusable, custom instructions.
Format:
operator(operands) // calling a function
return result // returning a value
Example:
result = sqrt(49)
Format:
try {
// call risky functions in the try-block
} catch { // catch-block
case thrown: Type1 => Branch1
case thrown: Type2 => Branch2
case thrown: Type3 => Branch3
// etc.
case thrown: Throwable => default
} finally {
// finally-block,
do this if an exception was thrown or not
}
Example:
try {
var cmmd = readLine("-> ")
cmmd match {
case "deposit" =>
case "withdraw" =>
case _ => throw new
BadCommandException
}
} catch {
case e:NegativeAmountException =>
println("amount must be positive")
case e:InsufficientFundsException =>
println("Insufficient funds")
case e: BadCommandException =>
println("Invalid command, type help")
case e: ATMException =>
println("Command failed")
case e: NumberFormatException =>
println("amount must be a number")
case _: Throwable => {
println("fatal error");
more = false
}
} finally {
println("...")
Console.flush()
}
In Java (C, C++) there are two ways to escape from a loop:
break; // end loop and go on to the next command
continue; // go back to
the top of the loop
For example, the loop:
for(int i = 0; i < 100; i++) {
if (i % 3 == 0) continue; // skip if i divisible by 3
if (i == 10) break; // terminate loop when i is 10
System.out.println("i = " + i);
}
System.out.println("done");
Should print:
i = 0
i = 1
i = 2
i = 4
i = 5
i = 7
i = 8
done
Although break and
continue aren't in the Scala, a more general form of break can be imported from
the scala library:
import scala.util.control.Breaks._
object TestBreak {
def main(args:
Array[String]): Unit = {
println("entering
main")
breakable
{
println("A")
breakable
{
println("B")
break
println("C")
}
println("D")
break
println("E")
}
println("exiting
main")
}
}
Output:
entering main
A
B
D
exiting main