Exception hierarchy in java

In the last post, we have learned about the Exception handling in java. The exception hierarchy in java is the most important part to handle the exception. In java, there is a lot of exception but there is some rule to handle them so we need to take care of exception class hierarchy in java. As of now, you might not be able to understand the benefit of the hierarchy of exception but when you will work on a big project you have to use the particular exception that occurs at a time. Let’s discuss with example:

Suppose you are writing a program of String concatenation and you want to join the string. But there is one object having null. It will throw NullPointerException. According to best practices, you should place NullPointerException between the braces of catch. Even you can place Exception between the braces of catch.

public  class ExceptionHandling 
{
	public static void main(String[] args) 
    {
	   try
	   {
		   String str = null;
		   str.concat("Hi");
	   }
	   catch(NullPointerException e)
	   {
		   e.printStackTrace();
	   }
   }
}

Output: java.lang.NullPointerException
at ExceptionHandling.main(ExceptionHandling.java:8)

The most common question of the interview which is the class at the top of exception class hierarchy is? The answer is simple, Throwable is a superclass of all exception classes. All the classes which are used to handle exceptions and errors are subclasses of Throwable. It is subdivided into two branches one branch is Exception and another is Error.

Exception hierarchy in java

 java.lang.Exception

All exception classes are a subclass of the java.lang.Exception class. If a user doesn’t know about the exception, then he/she can provide the Exception class in the catch block. But it doesn’t consider as good programming.

Let’s take an example to explain the use of Exception class: In this example, the user doesn’t know what type of exception was thrown by the system. If you don’t know anything about exception you can directly use Exception class because it will automatically handle all the subclasses.

public class ExampleOfException 
{
	public static void main(String[] args) 
        {
		int a = 25;
		try
		{
			int b = a/0;    //it will throw exception
		}
		catch(Exception e)
		{
			System.out.println(e);
		}
	}
}

Error

some types of errors may be coming at runtime and this type of error is indicated by JVM. For example, hardware failure or out of memory error. These types of situations are not handling by any programmer because they are unpredictable.

Leave a Comment