Java threads, interrupted exception correct handling

Advertisements

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

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.

Leave a ReplyCancel reply