开发者

SCJP: Program not terminating after uncaught exception

public class Threads2 implements Runnable {

开发者_JAVA百科    public void run() {
        System.out.println("run.");
        throw new RuntimeException("Problem");
    }

    public static void main(String[] args) {
        Thread t = new Thread(new Threads2());
        t.start();
        System.out.println("End of method.");
    }
}

I predicted the output as

run.
//exception

But it is showing output as,

run
exception
end of method

(or)

run
end of method
exception

I wonder, once the exception has occurred the program will terminate, right?


No, your program does not terminate, but the thread does.

When a thread throws an uncaught exception it terminates. Your main thread continues running.


First thing, the output you got is not the final. It depends on machine in case of multi-threading. On different machine some different output might come.

On exception, the running thread execution terminates. Other thread continue their execution.


See for yourself. On my machine I get:

bartek@dragon:~/workspace/sandbox$ java Threads2 
End of method.
run.
Exception in thread "Thread-0" java.lang.RuntimeException: Problem
    at Threads2.run(Threads2.java:5)
    at java.lang.Thread.run(Thread.java:636)


This is the beauty of multithreading!!

Every java program you write has a thread running it which is normally a main thread. In your case you have created your own thread whose parent thread is main thread. When your child thread throws an exception, it ends but main thread is still not complete. So it prints is last statement and then ends.

In case of threads the behavior can not be predicted [as it depends on JVM's policy to pick items from runnable pool] so the order you see might be different in different runs.


If you observe the question you are creating a thread t explicitly. when you run code main method will run, here jvm will create a thread for main class also. that means there are two threads for the code. one is t and other is main class thread. Here main() thread is parent thread and the t thread is child thread. As the exception occurs in child thread it gets terminated and the parent thread will run. So the output might be any of the order.

Regards, James


Not program but thread terminates. Main program continues execution.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜