I assume you mean this code segment:
try { boolean b = true; while (true) { b = !b; } } catch(Exception e) { System.out.println("exception happened hurray!"); }
The reason you cannot catch an InterruptedException here is because there is nothing inside this block that can throw an InterruptedException . interrupt() itself will not snatch the thread out of the loop, instead, it essentially sends a signal to the thread to tell it to stop what it is doing and do something else. If you want interrupt() break the loop, try the following:
boolean b = true; while (true) { b = !b; // Check if we got interrupted. if(Thread.interrupted()) { break; // Break out of the loop. } }
Now the thread checks to see if it is interrupted and exits the loop after it is completed. No try-catch .
Minty fresh
source share