Exceptions In Java: Hierarchy, Types & Its Relation With Errors

Exceptions In Java: Hierarchy, Types & Its Relation With Errors
Exceptions In Java: Hierarchy, Types & Its Relation With Errors

Introduction

To err is human! It means it is normal for people to make mistakes.

The above phrase does not apply to machines. Computers, for that matter, are incapable of ignoring errors. Suppose a programmer needs to open a file to do some modifications. And the file is missing from its desired destination. The computer will display an error message, and the program will be terminated.

In Java, “Exceptions are unwanted disruptions in the normal flow of the program’s execution.” They signify that something went wrong during the execution of the program.


Dealing with such coding errors is an integral part of every programmer’s life. Anyone who develops and manipulates computer code, regardless of their level of education or experience, may encounter various errors from time to time.

This article is part of a four-blog series on Java exceptions and exception handling. The introduction, hierarchy, built-in, user-defined exceptions and the fundamental differences between exceptions and errors are covered in this part.

Here’s a step-by-step guide to help you get the most out of this series.

This may sound daunting at first, but once you’ve completed the series, exceptions in Java will be a breeze for you.

Hierarchy of Exceptions In Java

Java is an object-oriented language, and it has a plethora of built-in classes and packages. The lang package of Java provides classes that are fundamental to the design of the Java language. For example, the Object class is part of this package, which is the default parent class of all Java classes. 

The root class of the Java exception is Throwable, which is a subclass of the Object class. Exception and Error both the classes are derived from the Throwable class.

Refer to the diagram given below to understand the hierarchy of exceptions in Java along with their category of checked and unchecked exceptions:

blog banner 1

Types of Exception in Java

The above diagram shows the two types of exceptions, checked and unchecked, based on the time of occurrence, i.e. compile-time or run-time. Despite the fact that Java has a rich library of predefined or built-in exceptions, it allows programmers to create their own exceptions. 

Considering the above fact, exceptions in java can also be classified as built-in and custom exceptions. We’ll go over the built-in type and creation of custom or user-defined exceptions in this section.

Built-in Exceptions

Exceptions that are available in Java libraries are known as built-in exceptions.

Most of these exceptions are subclasses of RuntimeExceptions defined in java.lang package. Since this package is imported to all the Java programs implicitly, most exceptions derived from RuntimeException are automatically available.

These exceptions are appropriate for explaining particular error situations. Below are some of the notable Java built-in exceptions.

ArithmeticException

This exception occurs when a program encounters an error in arithmetic operations such as divide by zero. 

The program given below demonstrates ArithmeticException


import java.io.*;

public class TestClass {
public static void main(String args[])
    {
            int num1 = 100, num2 = 0;
            int result = num1 / num2; // divide by zero
            System.out.println("Result = " + result);
    }
}

Output
Exception in thread "main" java.lang.ArithmeticException: / by zero
	at TestClass.main(Test.java:8)

ArrayIndexOutOfBoundsException:

This exception is thrown when an array is accessed using an illegal index. The index used is either more than the size of the array or is a negative index. Java doesn’t support negative indexing.

The program given below demonstrates ArrayIndexOutOfBoundsException


import java.io.*;

public class TestClass {
	public static void main(String args[])
    {
        int a[] = new int[6];
        System.out.println(a[6]);
         //indexing starts with zero
        // accessing 7th element in an array of size 6
    }
}

Output
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 7 out of bounds for length 6 
at TestClass.main(Test.java:6)

ClassNotFoundException

This exception is thrown when the JVM tries to load a class, which is not present in the classpath. 

The program given below demonstrates ClassNotFoundException


// When we try to run a database connectivity program without adding // jar files to the classpath, a class not found exception arises.

public class Test{
    public static void main(String[] args)
    {
        Class.forName("oracle.jdbc.driver.OracleDriver");
       
    }
}

Output
Exception in thread "main" java.lang.Error: Unresolved compilation problem:     Unhandled exception type ClassNotFoundException
at Test.main(TestClass.java:5)

FileNotFoundException:

This exception is thrown when the program tries to access a file that does not exist or does not open. This error occurs mainly in file handling programs.

The program given below demonstrates FileNotFoundException


import java.io.*;
public class TestClass {
  
public static void main(String args[])
    {
        // Following file does not exist in the location mentioned
            File file = new File("E:// file.txt");
  
            FileReader fr = new FileReader(file);
        
    }
}

Output
Exception in thread "main" java.lang.Error: Unresolved compilation problem: Unhandled exception type FileNotFoundException
at TestClass.main(TestClass.java:9)

 

IOException:

This exception is thrown when the input-output operation in a program fails or is interrupted during the program’s execution.

The program given below demonstrates IOException


import java.io.*;

public class TestClass 
{
public static void main(String args[])
    {
        FileInputStream f = null;
        f = new FileInputStream("CodingNinjas.txt");
        int i;
        while ((i = f.read()) != -1) {
            System.out.print((char)i);
        }
        f.close();
    }
}

Output
Exception in thread "main" java.lang.Error: Unresolved compilation problems: Unhandled exception type IOException
	at TestClass.main(TestClass.java:6)

InterruptedException:

This exception occurs whenever a thread is processing, sleeping or waiting in a multithreading program and it is interrupted.

The program given below demonstrates InterruptedException


import java.io.*;

public class TestClass {
	public static void main(String args[])
    {
        Thread t = new Thread();
        t.sleep(10000);
    }
}

Output
Exception in thread "main" java.lang.Error: Unresolved compilation problem: Unhandled exception type InterruptedException
at TestClass.main(TestClass.java:6)

NullPointerException:

This exception is raised when a null object is referred to in a program. NullPointerException is the most important and common exception in Java.

The program given below demonstrates NullPointerException


import java.io.*;

public class TestClass {
	public static void main(String args[])
    {
        String a = null; // null value
            System.out.println(a.charAt(0));   
    }
}

Output
Exception in thread "main" java.lang.NullPointerException
at TestClass.main(TestClass.java:6)

NumberFormatException:

This exception is thrown when a method could not convert a string into a numeric format.

The program given below demonstrates NumberFormatException


import java.io.*;

public class TestClass {
	public static void main(String args[])
    {
        String a = null; // null value
            System.out.println(a.charAt(0));   
    }
}

Output
Exception in thread "main" java.lang.NumberFormatException: For input string: "CodingNinjas" at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)

 

StringIndexOutOfBoundsException:

This exception is thrown by the string class, and it indicates that the index is beyond the size of the string object or is negative.

The program given below demonstrates StringIndexOutOfBoundsException


import java.io.*;

public class TestClass {
	public static void main(String args[])
    {
     
            String a = "Coding Ninjas"; // length is 13
            char c = a.charAt(14); // accessing 14th element
            System.out.println(c);
        
    }
}

Output
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 14

EOFException:

This exception is a part of the java.io package and is thrown when the end of the file is reached.

The program given below demonstrates EOFException.


import java.io.*;
import java.util.Scanner;

public class TestClass {
   public static void main(String[] args) throws Exception {
      //Reading from the file using readChar() method
      DataInputStream dis = new DataInputStream(new FileInputStream("D:\\data.txt"));
      while(true) 
      {
         char ch;
            ch = dis.readChar();
            System.out.print(ch);
         
      }
}
}

Output
Exception in thread "main" java.io.EOFException 	at java.base/java.io.DataInputStream.readChar(DataInputStream.java:370)
at TestClass.main(TestClass.java:10)

illegalArgumentException:

This exception is thrown when invalid arguments are passed to any method in the program. 

The below Java program demonstrates the IllegalArgumentException.Output


//Every thread has a priority, which is a number between 1 and 10
import java.io.*;
public class TestClass {
	public static void main(String[] args)
    {
        Thread t = new Thread();
        Thread t1 = new Thread();
        t.setPriority(7); // Correct
        t1.setPriority(17); // Exception
    }
}

Output
 
Exception in thread "main" java.lang.IllegalArgumentException
	at java.base/java.lang.Thread.setPriority(Thread.java:1141)
	at TestClass.main(TestClass.java:8)

Other Important Built-in Exceptions in Java

  • NoSuchFieldException: If a class in a program does not contain a specified field or variable, it throws this exception.
  • NoSuchMethodException: This exception is raised when the method being accessed is not found.
  • InputMismatchException: This exception is thrown when the input read does not match a pattern specified. For example, if the program expects an integer and reads a float value. 
  • NoSuchElementException: This exception is thrown when the next element accessed in a program does not exist.
  • ConcurrentModificationException: This exception is usually thrown by Collection classes. This exception is thrown when the objects try to modify a resource concurrently in a program.

User-defined Exceptions

So far, we’ve covered exceptions that the Java language has to offer as built-in/pre-defined java exceptions. In addition to these, we can also create our exceptions as per the requirement.

Such exceptions are called custom exceptions or user-defined exceptions.

For Example, If a user wants to make a program accepting candidates with age 18 or more. A custom exception for this problem can be created in the following manner.

Step: 1 Create a custom class:

A custom class is created defining the functionality needed to offer.

Step: 2 Choose a Superclass for the custom class:

The custom class we have created needs to extend any exception subclass from the hierarchy. However, choosing a random class can be ineffective. Because either they are too specialised or irrelevant to our custom class. So, the best practice is to extend the Exception class itself.

class CustomException extends Exception{  
 CustomException(String s){  
  super(s);  
 }  
} 

Step: 3 Use custom class in the program 

The program is throwing the custom exception while validating age in the if clause.

class TestCustomException
{  
  static void validate(int age)throws CustomException
  {  
     if(age<18)throw new CustomException("Invalid Age");  
     else  
      System.out.println("Successful!!");  
   }  
     
   public static void main(String args[])
   {  
      try {  
      validate(13);  
      } catch(Exception ex)
      {
    	  System.out.println("Exception occured: "+ex);
      } 
  }  
}  

Output

Invalid Age

Note: It’s fine if you’re a beginner and have no idea what these terms mean or how they have been used in the code above. This series is designed to assist you in understanding this topic at all levels. All these terms are thoroughly explained in the topics listed in the introductory part. So don’t be discouraged and keep learning.

The significant factor behind the magic of exceptions in Java is JVM. JVM  is short for Java Virtual Machine, which is an abstract machine. It is a specification that provides a runtime environment for executing Java bytecode.

Let’s take a closer look at JVM’s role in the mechanism of exception.

Mechanism of Exception Handling: Role of JVM

If an exception occurs inside a method, the method creates an Exception Object and sends it off to the run-time system or JVM. Exception Object contains the name, description and current state of the program where the exception has been raised. 

The process of creating an exception object and handing it to JVM is known as throwing an exception. A list of methods could be called to go to the method where the exception occurred.

This list of the methods is called Call Stack

The Call Stack

The step by step procedure of exception handling by JVM  is given below:

  • The JVM looks through the call stack for an exception handler that can handle the exception. 
  • The JVM begins its search at the method where the exception occurred and works backwards across the call stack, calling methods in the same order they were called.

Searching the call stack for the exceptional handler

  • If a suitable handler is found, the JVM forwards the thrown exception to it. The type of the exception object thrown must match the type of the exception object the handler can handle.
  • If the JVM explores all of the methods on the call stack and cannot find an appropriate handler, the Exception object is sent to the default exception handler, which is part of the run-time system. This handler prints the exception information and aborts the program.

Exception vs Errors

Considering the hierarchy of Exceptions in Java as explained above, it can be concluded that both Error and Exception are subclasses of the Throwable parent class. 

The table below shows some of the key differences between exception and error

ErrorsException
A lack of system resources typically causes errors in a program, and the program that a programmer writes is not designed to detect such issues. An exception occurs mainly due to issues in programming such as bugs, typos, syntax errors, etc.
Errors usually happen at runtime. Therefore they’re of the unchecked type.Exceptions can arise at both runtime and compile-time.
System crashes and out-of-memory errors are two instances of errors. SQLException is an example of exceptions in Java
Errors belong to java.lang.error.Errors belong to java.lang.Exception.
Errors are irrecoverable and lead to abnormal termination of the program.Exceptions are recoverable and can be handled by exception handling techniques.

Frequently Asked Questions

What are Exceptions in Java?

Exceptions in Java are unwanted disruptions in the normal flow of the program’s execution.

What is the difference between error and exception in Java?

1. Errors are caused by the environment in which the program is running. For example: When a JVM runs out of memory, OutOfMemoryError occurs.
2. Exceptions, on the other hand, are mainly caused by the bugs in a program. For example: When an application tries to access a null object, NullPointerException occurs.

Can we create an exception?

Yes, we can create custom exceptions in Java.

How Does Exception Handling Work in Java?

If an exception occurs inside a method, the method creates an Exception Object and sends it off to the run-time system. Now, the JVM searches for an exception handler to handle the exception.

Why do we need Java Exception Handling?

In Java, exception handling is required to prevent the program from terminating unexpectedly.

What is the parent class of the exception class?

Throwable class is the parent class of the Exceptions in Java.

Key Takeaways

To deal with unusual scenarios in the program, a programmer must understand the concept of exceptions in detail. This blog throws light on the basics of exceptions in Java along with its different types. Once you have read this article thoroughly, it is recommended that you must visit our blog on checked vs unchecked exceptions in Java and the subsequent parts for a better understanding of this topic.

Java is a powerful general-purpose, object-oriented programming language used to develop mobile applications, web applications, big data processing, embedded applications and is supported by billions of devices worldwide.

Aspire to become the next face of Java Developer? Don’t miss checking out our Java Foundation course with Data Structures & Algorithms and Java Cheat Sheet equipped with the knowledge of Data Structures and Algorithms plus the proper understanding of the rich API and powerful development tools of programming.

By Vaishnavi Pandey