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:
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. |
In this Answer, we learned about various types of exceptions that can occur in Java, their hierarchy, and what they are.
RELATED TAGS
CONTRIBUTOR
View all Courses