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 InterruptedException, 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.
But consider why your thread was interrupted in first place. As Ole put it: Stop doing what you were doing. If need be perform some cleanup work, then exit.
This may mean you have to exit the loop. It may mean you have to stay in the loop, or run some 'undo' loop. But in any case you have to deal with the fact that this thread actually needs to terminate. And since throwing an InterruptedException clears the interrupted flag of the thread, generally it is wise to set the interrupted flag again using Thread.currentThread().interrupt()
.
If your application needs to perform cleanup also see Runtime.addShutdownHook(), as similar concepts will apply to an interrupted thread:
Shutdown hooks should also finish their work quickly. When a program invokes exit the expectation is that the virtual machine will promptly shut down and exit. When the virtual machine is terminated due to user logoff or system shutdown the underlying operating system may only allow a fixed amount of time in which to shut down and exit. It is therefore inadvisable to attempt any user interaction or to perform a long-running computation in a shutdown hook.