Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Java threads, interrupted exception correct handling

Why second example is better than the first one? Can someone explain me?

//1

public void run()
{
    while (. . .)
    {
        . . .
        try 
        { 
            Thread.sleep(delay); 
        } catch (InterruptedException exception) {}  
            . . .
        }
    }
}

//2

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

public void run() {
    try {
        while (. . .) {
         . . .
         Thread.sleep(delay);
         . . .
        }
    } catch (InterruptedException exception) {
    } 
}

I heard that the first example, when InterruptedException occurs it does not terminate the thread, but I still do not understand why.

>Solution :

Neither is better – it depends on what you intend to do.

The second example would break the while loop upon InterruptedException,
the first example will just break one iteration and the thread would continue on the next.

The reason is that an exception, when thrown inside Thread.sleep() will break all execution until a catch block applies (or, if none such block is found, the thread terminates). In the second example this catch is outside the loop, therefore after having executed the catch the loop is gone.

Given what you want to achieve either one or the other is the way to go.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading