Java Program to Use Exceptions with Thread - GeeksforGeeks

01 Dec, 2020
Exceptions are the events that occur due to the programmer error or machine error which causes a disturbance in the normal flow of execution of the program. When a method encounters an abnormal condition that it can not handle, an exception is thrown as an exception statement. Exceptions are caught by handlers(here catch block). Exceptions are caught by handlers positioned along with the thread’s method invocation stack. If the calling method is not prepared to catch the exception, it throws the exception up to its calling method and so on. So in the java program exception handlers should be positioned strategically, so the program catches all the exception from which the program want to recover.
Lifecycle of a thread: The class implements a Thread class or Runnable interface then the extended class has start() method run the thread, sleep() methods cause the currently executing thread to sleep for the specified number of milliseconds, and many more.                         
Prior to discussing the approaches, state. transactions of thread should be known to further deal with exceptions for better understanding. A thread in Java at any point in time exists in any one of the following states. A thread lies only in one of the shown states at any instant:
NewRunnableBlockedWaitingTimed WaitingTerminated
New
Runnable
Blocked
Waiting
Timed Waiting
Terminated
1. A class name RunnableThread implements the Runnable interface which gives the run( ) method executed by the thread. The object of this class is now runnable
2. The Thread constructor is used to create an object of RunnableThread class by passing the runnable object as a parameter.
3. The start() method is invoked on the Thread object as it returns immediately once a thread has been spawned.
4. The thread ends when the run( ) method ends which is to be normal termination or caught exception.
5. Now in order to create a new thread
runner = new Thread(this,threadName) ;
6. In order to start the new thread.
runner. start() ;
7. public void run( ) is an overrideable method used to display the information of a particular thread.
8. Thread.currentThread().sleep(2000) is used to deactivate the thread until the next thread started execution or used to delay the current thread.
Uncaught exception handler will be used to demonstrate the use of exception with thread. It is a specific interface provided by Java to handle exception in the thread run method.
There are two methods to create a thread: 
Extend the thread Class (java.lang.thread)Implement Runnable Interface (java.lang.thread)
Extend the thread Class (java.lang.thread)
Implement Runnable Interface (java.lang.thread)
1. Exception and Exception handling with threads
Here, a new thread is created in the class which is extending the thread class in which run() method is overridden. This invokes the entry point of the new thread created in the class which was extending the thread class. Further, start() method is used to start and run the thread in the program. 
Java
// Java program to Use exceptions with thread  // Importing Classes/Filesimport java.io.*;  // Child Class(Thread) is inherited from parent Class(GFG)class GFG extends Thread {      // Function to check if thread is running    public void run()    {        System.out.println("Thread is running");          // Using for loop to iterate        for (int i = 0; i < 10; ++i) {            System.out.println("Thread loop running " + i);        }    }      // Main Driver Method    public static void main(String[] args)    {          // Try-catch block to detect exception        try {              // Creating new thread            GFG ob = new GFG();              throw new RuntimeException();        }          // Catch block to handle exception        catch (Exception e) {              // Exception handler            System.out.println(                "Another thread is not supported");        }    }}
Output:
Another thread is not supported
2. Exception handling with sleep method(): sleep() method of thread class is used where there is a demand to sleep the thread for a particular period of time for the proper workflow of the code.
Syntax:
public static void sleep(long milliseconds) ;                                  // generally used
public static void sleep(long milliseconds, int nanoseconds) ;      // used to illustrate the precision only 
Parameter: 
Name
Action performed
Return type: As seen in syntax itself, it does not return any value.
Exception: It does often throws out exceptions as java language being involving the concept of multithreading
IllegalArgumentException is thrown when the parametric value is negative as it is bounded as discussed between [0 — +999999]InterrupteException is thrown when a thread is interrupted with an ongoing thread as discussed java supports the concepts of multithreading.
IllegalArgumentException is thrown when the parametric value is negative as it is bounded as discussed between [0 — +999999]
InterrupteException is thrown when a thread is interrupted with an ongoing thread as discussed java supports the concepts of multithreading.
Implementation:
Java
// Java program to Use exceptions with thread  /* Note: Dont confuse main method with Main class*/  // Importing Classes/Filesimport java.io.*;  // Child Class(Thread) is inherited// from parent Class(GFG)class GFG extends Thread {    public void run()    {        System.out.println("Throwing in "                           + "MyThread");        throw new RuntimeException();    }}  // Main driver methodpublic class Main {    public static void main(String[] args)    {        GFG t = new GFG();        t.start();          // try block to deal with exception        try {            Thread.sleep(2000);        }          // catch block to handle the exception        catch (Exception x) {            // Print command when exception encountered            System.out.println("Exception" + x);        }          // Print command just to show program        // run successfully        System.out.println("Completed");    }}
Output:
Throwing in MyThread
Exception in thread "Thread-0" java.lang.RuntimeException
        at testapp.MyThread.run(Main.java:19)
Completed
Java-Exception Handling
Technical Scripter 2020
Java
Java Programs
Technical Scripter
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Constructors in Java
Exceptions in Java
Functional Interfaces in Java
Different ways of Reading a text file in Java
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
How to Iterate HashMap in Java?
Iterate through List in Java