JavaMultithreading

Exceptions in threads

If one of the threads of your program throws an exception that is not caught by any method along the invocation stack, the thread will be terminated. If such an exception occurs in a single-thread program, the entire program will stop, because JVM terminates the running program as soon as there are no more non-daemon threads left.

Here is a tiny example:

public class SingleThreadProgram {
    public static void main(String[] args) {
        System.out.println(2 / 0);
    }
}

The program outputs:

Exception in thread "main" java.lang.ArithmeticException: / by zero
  at org.hyperskill.jcourse.multithreading.exceptions.SingleThreadProgram.main(SingleThreadProgram.java:6)

Process finished with exit code 1

The code 1 means the process finished with an error.

If we create and run a new thread, within which an error occurs, the process will not be stopped.

public class ExceptionInThreadExample {
    public static void main(String[] args) throws InterruptedException {
        Thread thread = new CustomThread();
        thread.start();
        thread.join(); // wait for thread terminates
        System.out.println("OK"); // this line will be printed
    }
}

class CustomThread extends Thread {

    @Override
    public void run() {
        System.out.println(2 / 0);
    }
}

Despite the uncaught exception, the program will be successfully completed.

Exception in thread "Thread-0" java.lang.ArithmeticException: / by zero  at org.hyperskill.jcourse.multithreading.exceptions.CustomThread.run(ExceptionInThreadExample.java:15)
OK

Process finished with exit code 0
The code 0 means the process successfully finished.

Thus, exceptions in different threads are handled independently. While the process has an alive non-daemon thread, it won't be stopped if an uncaught exception occurs. But the good practice is to handle exceptions in threads.
How did you like the theory?
Report a typo