In this program, we will handle an InterruptedException using try, catch block. The code that may generate an exception should be written in the "try" block, and the "catch" block is used to handle the exception and prevent program crashes.
Program/Source Code:
The source code to handle InterruptedException is given below. The given program is compiled and executed successfully.
//Java program to handle InterruptedException.
class MyThread extends Thread {
public void run() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
System.err.println("Exception: " + e);
}
}
}
public class Main {
public static void main(String[] args) {
MyThread thrd = new MyThread();
thrd.start();
thrd.interrupt();
}
}
In the above program, we created two classes MyThread and Main. The Main class contains a main() method. The main() method is the entry point for the program. The MyThread class is a thread class to create a thread in our program.
Here, we created "try" and "catch" blocks. In the "try" block, the InterruptedException gets generated because we created a thread and it is interrupted using the interrupt() method. And, handled generated exceptions using the "catch" block and printed exception message.
In this program, we will handle an InterruptedException using try, catch block. The code that may generate an exception should be written in the "try" block, and the "catch" block is used to handle the exception and prevent program crashes.
Program/Source Code:
The source code to handle InterruptedException is given below. The given program is compiled and executed successfully.
Output:
Explanation:
In the above program, we created two classes MyThread and Main. The Main class contains a main() method. The main() method is the entry point for the program. The MyThread class is a thread class to create a thread in our program.
Here, we created "try" and "catch" blocks. In the "try" block, the InterruptedException gets generated because we created a thread and it is interrupted using the interrupt() method. And, handled generated exceptions using the "catch" block and printed exception message.