Skip to content
Tutorials Center
My learning

Topics

Lesson 199 of 201 ยท Practice and Review

Exception and Thread Programs in Java

Practice Java exceptions and threads with runnable programs - multi-catch, Error vs Exception, unreachable code, thread states, sleeping safely, join, daemon threads and race conditions.

Exceptions and threads are the two parts of Java where a program can look fine and still do something surprising. The same short programs appear in textbooks, exams and interviews because each one tests a precise rule: what does dividing by zero really do, why won't this catch compile, is this thread alive yet, why is my counter lower than expected.

This page is a workbook of those programs. Every one is runnable, small enough to read in a minute, and followed by an explanation of the rule behind the output. Try to predict the output before you press Run. The theory lives in Exceptions and try-catch, Threads and Thread Lifecycle and Priorities.

Exception programs

Division by zero and multi-catch

Integer division by zero throws ArithmeticException, but floating-point division by zero does not: it produces Infinity, -Infinity or NaN. % follows the sign of the left operand. A single catch can handle several unrelated exception types with | (multi-catch), as long as none of the types is a subclass of another. Order catches from specific to general, and note that finally runs whether or not anything was thrown.

Java Multi-catch, finally and floating-point division

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

10 / 4 prints 2 because both operands are int. The store case shows a less common unchecked exception: arrays remember their real element type, so putting a String into an array that was created as Integer[] fails at run time with ArrayStoreException, even though the code compiled.

Error versus Exception

Throwable has two branches. An Exception describes something a program can reasonably handle (a missing file, bad input). An Error reports a failure of the JVM itself, such as running out of memory or stack, and normally should not be caught. Among exceptions, RuntimeException and its subclasses are unchecked: the compiler does not force you to handle them. Every other exception is checked and must be caught or declared with throws.

The program triggers one example of each family and classifies what it caught.

Java Error, unchecked and checked exceptions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Catching Throwable as this program does is acceptable in a test harness that must report anything that goes wrong, but in application code you catch the narrowest type you can actually handle. The last line shows the family tree: StackOverflowError is a VirtualMachineError, which is an Error. The wrapped IOException is the usual way to smuggle a checked exception through code that cannot declare it, and getCause() still holds the original.

Unreachable code and impossible catches

The compiler does flow analysis and rejects some code outright. A statement that can never run is a compile error, not a warning, and so is a catch for a checked exception that nothing in the try can throw, or a catch that an earlier one already covers. These snippets do not compile; the messages below are the real ones from the compiler.

Java
static int a() {
    return 1;
    IO.println("after return");          // error: unreachable statement
}

static void b() {
    throw new IllegalStateException();
    int x = 1;                           // error: unreachable statement
}

static void c() {
    while (true) {
    }
    IO.println("after loop");            // error: unreachable statement
}

static void d() {
    for (int i = 0; i < 3; i++) {
        break;
        IO.println("after break");       // error: unreachable statement
    }
}

static void e() {
    try {
        IO.println("x");
    } catch (java.io.IOException ex) {   // error: exception IOException is never thrown
    }                                    //        in body of corresponding try statement
}

static void f() {
    try {
        Integer.parseInt("1");
    } catch (RuntimeException ex) {
    } catch (NumberFormatException ex) { // error: exception NumberFormatException has already been caught
    }
}

Note that if (false) { ... } is deliberately allowed: the language makes an exception so that conditional-compilation flags can be written as constants. A catch (Exception e) is also always legal, because Exception includes unchecked exceptions that might be thrown anywhere. See Throwing Exceptions for throw and throws.

Thread programs

Checking a thread's status and pausing safely

getState() reports where a thread is in its life: NEW before start(), TIMED_WAITING while it sleeps, TERMINATED after it finishes. isAlive() is true between start() and termination. Thread.sleep pauses the current thread and throws the checked InterruptedException if another thread interrupts the sleeper. The safe way to handle that is either to exit the work, as below, or to restore the interrupt flag with Thread.currentThread().interrupt() so callers still see it. Never swallow it silently. Since Java 19 there is also Thread.sleep(Duration).

Java Thread states, interrupted sleep and a safe pause

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

When a thread catches InterruptedException, the interrupt flag is cleared, which is why the first thread prints flag now false. A pause is a minimum: the scheduler may wake the thread a little later, never earlier.

join and daemon threads

join() makes the calling thread wait until another thread has finished, which is how you collect results from workers. A daemon thread is a background helper (a heartbeat, a cache cleaner): the JVM exits when only daemon threads are left, without waiting for them. setDaemon(true) must be called before start(); afterwards it throws IllegalThreadStateException. Anything a thread wrote before it ended is guaranteed visible to the thread that joined it.

Java join workers and a daemon heartbeat

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Without the join loop, main could print results before the workers wrote anything. The sums are 1 + ... + 100, 1 + ... + 200 and 1 + ... + 300, using the formula n(n+1)/2.

Thread interference

When two threads update the same variable without coordination, updates can be lost. count++ looks like one step but is three: read, add one, write back. If both threads read the same old value, both write the same new value, and one increment disappears. That is thread interference, also called a race condition. The fixes are a lock (synchronized), or an atomic class that performs the whole read-modify-write as one operation.

Java Lost updates versus synchronized and atomic

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The plain result changes from run to run, which is typical for races: sometimes it is even correct by luck, and that is exactly why such bugs survive testing. The program prints a description instead of the raw number so the explanation stays true on any machine. See Synchronization and Atomic Variables.

Memory consistency

The second problem is visibility. Even without a race on a value, one thread might not see another thread's write for a long time, because each core may keep its own cached copy and the compiler may reorder instructions. The Java Memory Model defines happens-before rules that make writes visible: writing a volatile variable and then reading it, releasing a lock and then acquiring the same lock, starting a thread, and finishing a thread followed by join().

Java volatile flag and join as visibility guarantees

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Because ready is volatile, everything the main thread wrote before ready = true (including the plain field payload) is visible to the reader once it sees ready == true. With a plain boolean, the reader could loop forever or see a stale payload; whether that actually happens on a given run depends on the JIT and the hardware, which is the point: you cannot test your way to correctness here. volatile gives visibility but not atomicity, so volatile int count; count++ is still a race. Read more in Synchronization.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does IO.println(10.0 / 0) print?

    Floating-point division by zero follows IEEE 754 and gives Infinity (or -Infinity). Only integer division by zero throws ArithmeticException. 0.0 / 0 gives NaN.
  2. 2. Which of these can be listed together in one multi-catch, catch (A | B e)?

    The alternatives of a multi-catch must not be subclasses of each other. IOException is an Exception, and NumberFormatException is an IllegalArgumentException, so those fail. Arithmetic and array index exceptions are unrelated siblings.
  3. 3. Why does the compiler reject catch (IOException e) around code that cannot throw an IOException?

    For checked exceptions, javac verifies that the try body can actually throw them. catch (Exception e) is the exception to the rule because it also covers unchecked exceptions.
  4. 4. When must setDaemon(true) be called?

    Changing the daemon status of a thread that has already started throws IllegalThreadStateException, so call setDaemon before start.
  5. 5. Two threads each run counter++ 100,000 times on a shared int. The final value is often below 200,000. Why?

    The increment is not atomic. Both threads can read the same old value and write back the same new value, losing one update. Use synchronized or an AtomicInteger.

Summary

  • Integer division by zero throws ArithmeticException; floating-point division gives Infinity, -Infinity or NaN.
  • Use multi-catch (A | B) for unrelated exception types; order catch blocks from specific to general; finally always runs.
  • Error means a JVM-level failure; RuntimeException is unchecked; other exceptions are checked and must be caught or declared.
  • Unreachable statements, a catch for a checked exception nothing throws, and a catch hidden by an earlier one are compile errors.
  • getState() and isAlive() report a thread's status; handle InterruptedException by stopping or by restoring the interrupt flag.
  • join() waits for a thread; daemon threads do not keep the JVM alive and must be set before start().
  • Without coordination, count++ loses updates; fix it with synchronized or atomic classes, and use volatile or locks for visibility.

Next: back to the exercises to practice without the answers in front of you.