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.
There are two kinds of exceptions in Java:
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.
Unchecked exceptions: These are the exceptions that are not checked by the compiler at compile time. They include runtime exceptions and errors.
The exception class hierarchy in Java is as follows:
The Throwable
class is the superclass of all exceptions and errors in Java. All other exception classes are subclasses of the Throwable.
The table given below represents some of the commonly used checked exceptions in Java with their description.
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. |
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.
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. |
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.
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. |
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 examplepublic static void readDataFromFile() {try {// Simulating an IO operation that may throw IOException// Instead of throwing the exception, handle it gracefullythrow 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 examplepublic static void divide(int a, int b) {try {// Simulating an arithmetic operation that may throw ArithmeticExceptionif (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 examplepublic static void causeOutOfMemoryError() {try {// Simulating an out of memory situationint[] 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 handlingreadDataFromFile();// Demonstrating unchecked exception handlingdivide(10, 0); // This will cause an ArithmeticException// Demonstrating error handlingcauseOutOfMemoryError();}}