I have a code that looks like this (I put everything into a single method just for shorter code).
public static void main(String[] args) {
@lombok.Data
class Data {
Data previous;
String text;
public Data(Data data) {
this.text = data.text;
}
public Data(String text) {
this.text = text;
}
}
class PlainThread implements Runnable {
private Data data;
public PlainThread(Data data) {
this.data = data;
}
@Override
public void run() {
int i = 0;
while (i != 5) {
// application stops but no notification of exception
System.out.println(data.previous.text);
ThreadUtils.delaySeconds(1);
i++;
}
}
}
System.out.println("Starting...");
Data data = new Data("Simple text");
// application fails there
// System.out.println(data.previous.text);
PlainThread thread = new PlainThread(new Data("Simple text"));
ExecutorService executorService = Executors.newFixedThreadPool(2);
executorService.submit(thread);
executorService.shutdown();
}
Basically I create object Data
that contains the reference to another Data
object which is null by default. I put this object in the thread that supposed to get the field text
of this another object. As I did not set previous
when I instantiated the object
Data data = new Data("Simple text");
I put the thread into the ExecutorService
. I expected to receive Null Pointer Exception
in console and application failure inside this thread loop
while (i != 5) {
// application stops but no notification of exception
System.out.println(data.previous.text);
ThreadUtils.delaySeconds(1);
i++;
}
But I don't get the notification (or stack trace in console) that exception occurs.
If I wrap System.out.println
into try-catch block inside the while loop
try {
// application stops but no notification of exception
System.out.println(data.previous.text);
} catch (Exception exc) {
System.out.println(exc);
}
It prints out the exception java.lang.NullPointerException
.
Why it's happening? Why it doesn't show exception in console like
Exception in thread "main" java.lang.NullPointerException
at com.xxx.Main.main(Main.java:83)
Edit: The question is not the duplicate to How to catch an Exception from a thread as I don't ask how to catch the exception but ask why it doesn't notify about the exception.