Rendering thread exception java

Java Program to Use Exceptions with Thread

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:

  1. New
  2. Runnable
  3. Blocked
  4. Waiting
  5. Timed Waiting
  6. 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

Читайте также:  Initialize local variables java

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.

7. public void run( ) is an overridable 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:

  1. Extend the thread Class (java.lang.thread)
  2. 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 Concurrent multithreading exception handling

2. Two strategies of multithreading exception handling

2-1. Try catch manually in the child thread (not recommended)

public class ThreadException implements Runnable @Override public void run()  try  throw new RuntimeException("Run err. "); > catch (Exception e)  System.out.println("Thread err warning. "); > > public static void main(String[] args) throws InterruptedException  new Thread(new ThreadException()).start(); Thread.sleep(1000); new Thread(new ThreadException()).start(); Thread.sleep(1000); > > // Operation result Thread err warning.... Thread err warning.... 

2-2. UncaughtExceptionHandler exception handling provided in thread class

This exception handler can be designed for different dimensions

  • Design an exception handler for the program
  • Each thread is designed separately
  • Design a line pool
// Define an exception handler public class MyUncaughtExceptionHandler implements Thread.UncaughtExceptionHandler  private String handlerName; public MyUncaughtExceptionHandler(String handlerName)  this.handlerName = handlerName; > @Override public void uncaughtException(Thread t, Throwable e)  System.out.println("Exception caught, processor:" + this.handlerName); System.out.println("Abnormal information: threadName:" + t.getName() + " e:" + e); > > // Use exception handler public class ThreadException implements Runnable @Override public void run()  throw new RuntimeException("Run err. "); > public static void main(String[] args) throws InterruptedException  Thread.setDefaultUncaughtExceptionHandler(new MyUncaughtExceptionHandler("Exception handler A")); new Thread(new ThreadException()).start(); > > // Operation result //Exception caught, processor:Exception handler A //Abnormal information: threadName:Thread-0 e:java.lang.RuntimeException: Run err... 

Источник

Thread Exception in Java | Exception in Thread

Scientech Easy

Thread Exception in Java | When we call a sleep() method in a Java program, it must be enclosed in try block and followed by catch block.

This is because sleep() method throws an exception named InterruptedException that should be caught. If we fail to catch this exception, the program will not compile.

JVM (Java Runtime System) will throw an exception named IllegalThreadStateException whenever we attempt to call a method that a thread cannot handle in the given state.

For example, a thread that is in a sleeping state cannot deal with the resume() method because a sleeping thread cannot accept instructions. The same thing is true for the suspend() method when it is used on a blocked thread.

When we call a thread method that may throw an exception, we will have to use an appropriate exception handler to catch it. The catch block may take one of the following forms:

1. catch(ThreadDeath e) < . . . . . . . . . . . . . // Killed thread >2. catch(InterruptedException ie) < . . . . . . . . . . . . . // Cannot handle it in the current state. >3. catch(IllegalArgumentException e) < . . . . . . . . . . . . . // Illegal method argument. >4. catch(Exception e) < . . . . . . . . . . . . . // Any other >

Exceptions in Main Thread

In this section, we will see some common main thread exceptions that may occur in different scenarios. They are as follows:

1. Exception in thread main java.lang.UnsupportedClassVersionError: This exception occurs in a program when a java class is compiled from another JDK version and we are trying to run it from another java version.

The UnsupportedClassVersionError is present java.lang package.

2. Exception in thread main java.lang.NoClassDefFoundError: This exception occurs in two flavors. The first scenario is where we provide class full name with .class extension. The second scenario comes when Class is not found.

3. Exception in thread main java.lang.NoSuchMethodError: main: This exception occurs in a Java program when a class is trying to run without the main method declaration.

4. Exception in thread main java.lang.ArithmeticException: When any exception is thrown from main method, it prints the exception in the console.

The first part explains that exception is thrown from the main method, second part prints the exception class name and then after a colon, it prints an exception message.

Hope that this tutorial has covered the basic points related to thread exception. I hope you will have understood this topic and enjoyed it.
Thanks for reading.
Next ⇒ Java Multithreading Interview Questions

Источник

Оцените статью