bhylu.com

Advertisements

Java Control Flow and Failure Vocabulary

Follow where execution can go next: a condition chooses a branch, a loop repeats work, and a transfer statement exits or changes the current flow. Exception handling provides a separate failure path.

Understand the idea

A switch expression produces a value and must cover its required cases. yield supplies that value from a block arm; it is not a return from the enclosing method. A catch handler matches the thrown type, while finally is normally used for cleanup that must accompany both success and failure. Prefer try-with-resources for owned AutoCloseable resources. The throws clause declares possible checked failures to callers; throw actually raises one. An assertion checks an internal assumption only when assertions are enabled and must not validate required public input.

Run it locally

Use a local JDK 21 or newer. Save the complete example as Main.java in a separate lab folder, then compile and run it with the commands below. Java examples do not run in Bhylu’s browser playground. The -ea option enables assertion checks used by some lessons.

JDK and terminal setup

javac --release 21 -encoding UTF-8 -d out Main.java
java -ea -cp out Main

A worked example

Java 21+ · Main.java

public class Main {
    public static void main(String[] args) {
        int seats = 3;
        String size = switch (seats) {
            case 1 -> "individual";
            case 2 -> "pair";
            default -> { String label = "group"; yield label; }
        };
        System.out.println(size);
        for (int i = 0; i < 4; i++) {
            if (i == 1) continue;
            if (i == 3) break;
            System.out.println(i);
        }
    }
}

Expected output

group
0
2

The default switch arm yields group from its block. The loop skips one, prints two and exits before printing three. continue moves to the next loop iteration; break exits this loop entirely. Neither statement returns from main. Trace the update expression as well as the body when deciding whether a for loop makes progress.

Contracts to look up

API or language termWhat to check
if, elseSelect a statement branch from a boolean condition.
switch, case, default, yieldSelect arms and produce values where the switch is an expression.
for, while, doRepeat work with different condition/update positions.
break, continue, returnExit a loop/switch, skip an iteration or finish a method.
try, catch, finallyAttempt work, handle matching failures and perform cleanup.
throw, throwsRaise a throwable or declare possible method failures.
assertOptional internal invariant check; enable with -ea during development.

Check the official Java documentation for detailed contracts and supported options.

Advertisements