Thread Exception in Java | Exception in Thread

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

⇐ Prev Next ⇒

Please share your love