What are different types of exceptions in Java?

Introduction

An exception is an event that occurs during the execution of a program that disrupts the normal flow of the program's instructions. In Java, exceptions are objects that describe an exceptional (error) condition that has occurred in a piece of code. They are used to handle errors and other exceptional events in programs written in the Java programming language.

Types of exceptions

There are two kinds of exceptions in Java:

  1. Checked exceptions: These are the exceptions that are checked by the compiler at compile time. If a method throws a checked exception, then the caller of the method must either handle the exception or declare it in the throws clause.

  2. Unchecked exceptions: These are the exceptions that are not checked by the compiler at compile time. They include runtime exceptions and errors.

Exception class hierarchy in Java

The exception class hierarchy in Java is as follows:

Exception hierarchy in Java

The Throwable class is the superclass of all exceptions and errors in Java. All other exception classes are subclasses of the Throwable.

Checked exceptions

The table given below represents some of the commonly used checked exceptions in Java with their description.

List of common checked exceptions in Java

Exception class

Description

IOException

This exception is raised when an input/output operation fails

SQLException

This exception is raised when a database operation fails

ClassNotFoundException

This exception is raised when a class cannot be found.

InstantiationException

This exception is raised when an object cannot be instantiated.

NoSuchMethodException

This exception is raised when a method cannot be found.

Unchecked exceptions

The RuntimeException class is the superclass of all unchecked exceptions. The table below represents some of the commonly used unchecked exception classes in Java with their description.

List of common unchecked exceptions in Java

Exception classes

Description



RuntimeException

This is the superclass of all unchecked exceptions.



NullPointerException:

This exception is raised when a null value is used where an object is required.



ArithmeticException

This exception is raised when an arithmetic operation fails.



ArrayIndexOutOfBoundsException

This exception is raised when an array index is out of bounds.



IllegalArgumentException

This exception is raised when an illegal argument is used.



IllegalStateException

This exception is raised when an illegal state is detected.



ConcurrentModificationException

This exception is raised when a collection is modified while it is being iterated over.



Errors

The Error class represents the serious problems that cause the program to abort. They include out of memory error, stack overflow error, and so on. Now, let's see different types of errors in Java.

Errors in Java

Error classes

Description

OutOfMemoryError

This error is raised when the JVM runs out of memory.

StackOverflowError

This error is raised when a stack overflow occurs.

VirtualMachineError

This is the superclass of all errors that occur in the JVM.

AssertionError

This error is raised when an assertion fails.

NoClassDefFoundError

This error is raised when a class cannot be found.

LinkageError

This error is raised when a linkage problem occurs.

ExceptionInInitializerError:

This error is raised when an exception occurs in the static initializer of a class.

Coding example

Now, let’s take a look at a coding example to understand exceptions by generating few exceptions.

import java.io.IOException;
public class ExceptionExample {
// Checked exception example
public static void readDataFromFile() {
try {
// Simulating an IO operation that may throw IOException
// Instead of throwing the exception, handle it gracefully
throw new IOException("Failed to read data from file");
} catch (IOException e) {
System.out.println("IOException caught: " + e.getMessage());
// Perform necessary error handling or recovery actions here
}
}
// Unchecked exception example
public static void divide(int a, int b) {
try {
// Simulating an arithmetic operation that may throw ArithmeticException
if (b == 0) {
throw new ArithmeticException("Division by zero");
} else {
int result = a / b;
System.out.println("Result of division: " + result);
}
} catch (ArithmeticException e) {
System.out.println("ArithmeticException caught: " + e.getMessage());
// Perform necessary error handling or recovery actions here
}
}
// Error example
public static void causeOutOfMemoryError() {
try {
// Simulating an out of memory situation
int[] array = new int[Integer.MAX_VALUE];
} catch (OutOfMemoryError e) {
System.out.println("OutOfMemoryError caught: " + e.getMessage());
// Perform necessary error handling or recovery actions here
}
}
public static void main(String[] args) {
// Demonstrating checked exception handling
readDataFromFile();
// Demonstrating unchecked exception handling
divide(10, 0); // This will cause an ArithmeticException
// Demonstrating error handling
causeOutOfMemoryError();
}
}

Conclusion

In this Answer, we learned about various types of exceptions that can occur in Java, their hierarchy, and what they are.