Since I don't know how much you know about Java, how java works exactly and what's concurrency, I'll try to explain as much as possible with nearly no background information needed.
At first we're going to take a look at Oracle's documentation of the InterruptedException
.
Thrown when a thread is waiting, sleeping, or otherwise occupied, and the thread is interrupted, either before or during the activity. [...]
What does this mean?
Before answering this question you have to rudimentary understand how a Thread
works.
A thread is originally just a piece of code that can be managed seperately from other threads. It can run at the same time (see concurrency), run scheduled, etc.
Example
If you start a normal java program the main()
method is created in an own thread 1. Everything you do will be executed in this thread. Every class you create, every method you call and basically everything that originated from main()
.
But if you create a Thread
, it runs in an own thread 2. Everything you do in the run()
method will be executed in thread 2.
What happens if you create a new Thread
?
The join()
method is called.
The join()
method starts the thread and run()
is being executed.
There's not only the join()
method with no parameters but also a join(long millis)
with a parameter.
When and why is it thrown?
As Rahul Iyer already said there's a variety of reasons. I'm picking some of them to get you a feeling when they're called.
- Timeout
The InterruptedException
can be indeed thrown when a timeout was exceeded. This happens when the join(long millis)
is called. The parameter specifies that the thread can run for the given amount of milliseconds. When the thread exceeds this timeout it is interrupted. source (from line 769 to line 822).
- OS is stopping the thread
Maybe the Operating System (Windows, Linux, Android, etc.) decided to stop the program. Why? To free resources, your program was mistaken as a virus, hardware is shutting down, the user manually closed it, etc.
An InterruptedException is thrown in the Thread
For example you're connected to the internet and you're reading something and the internet disconnects suddenly.
interrupt()
is called
As already mentioned, an InterruptedException
is also thrown, when you call the interrupt()
on any Thread
(quite logical).
How to handle it?
You can/should handle it like every other exception. Wrap it in a try
and catch
, declare that the method throws
it, log it, etc.
This may be the best resource for you: Handling InterruptedException in Java.