What are the exceptions of Java?

An exception is an unexpected event that occurs during program execution. It affects the flow of the program instructions which can cause the program to terminate abnormally.

An exception can occur for many reasons. Some of them are:

  • Invalid user input
  • Device failure
  • Loss of network connection
  • Physical limitations (out of disk memory)
  • Code errors
  • Opening an unavailable file

Java Exception hierarchy

Here is a simplified diagram of the exception hierarchy in Java.

What are the exceptions of Java?

As you can see from the image above, the Throwable class is the root class in the hierarchy.

Note that the hierarchy splits into two branches: Error and Exception.


Errors

Errors represent irrecoverable conditions such as Java virtual machine (JVM) running out of memory, memory leaks, stack overflow errors, library incompatibility, infinite recursion, etc.

Errors are usually beyond the control of the programmer and we should not try to handle errors.


Exceptions can be caught and handled by the program.

When an exception occurs within a method, it creates an object. This object is called the exception object.

It contains information about the exception such as the name and description of the exception and state of the program when the exception occurred.

We will learn how to handle these exceptions in the next tutorial. In this tutorial, we will now focus on different types of exceptions in Java.


Java Exception Types

The exception hierarchy also has two branches: RuntimeException and IOException.


1. RuntimeException

A runtime exception happens due to a programming error. They are also known as unchecked exceptions.

These exceptions are not checked at compile-time but run-time. Some of the common runtime exceptions are:

  • Improper use of an API - IllegalArgumentException
  • Null pointer access (missing the initialization of a variable) - NullPointerException
  • Out-of-bounds array access - ArrayIndexOutOfBoundsException
  • Dividing a number by 0 - ArithmeticException

You can think about it in this way. “If it is a runtime exception, it is your fault”.

The NullPointerException would not have occurred if you had checked whether the variable was initialized or not before using it.

An ArrayIndexOutOfBoundsException would not have occurred if you tested the array index against the array bounds.


2. IOException

An IOException is also known as a checked exception. They are checked by the compiler at the compile-time and the programmer is prompted to handle these exceptions.

Like most modern programming languages, Java includes the concept of exceptions to handle both errors and "exceptional events." When an exception occurs in your code, it disrupts the normal instruction logic and abnormally terminates the process.

However, with a little foresight and code, you can often handle these exceptions gracefully, allowing your code to continue running and providing insight for tracking down the root cause of the unexpected result.

In this article, we’ll take a brief look at how Java handles exceptions, the difference between checked and unchecked exceptions, and then walk through ten of the most common exceptions you’ll face in Java, and why they might occur.

How Java Handles Exceptions

When an exception occurs within a class or method, the method/class creates an exception object and hands the results to the runtime system (JVM).

The runtime system then travels over the call stack in order to determine what layer can handle the exception that was created or thrown. The search begins with the method in which the exception was created, then walks sequentially through the call stack until it finds an exception handler. When the type of exception matches a type that can be handled by the exception handler, it finds a match.

Consider the following stack trace example:

What are the exceptions of Java?

If an uncaught exception occurs in the Worker class, the exception will flow to the Service class. If no handler exists in the Service class, then the exception will flow through the stack trace to the Controller class. If the exception still does not have an appropriate handler, the exception will pass to the Application class, containing the

Example example = new Example();
Method method = Example.class.getMethod("divide");
Exception exception = assertThrows(Example.class, () -> method.invoke(example));
0 method and running the RESTful service.

Exceptions are important because they provide a mechanism to ensure program integrity and present a reliable code base. Failure to provide proper exception handling can result in exceptions flowing to the calling

Example example = new Example();
Method method = Example.class.getMethod("divide");
Exception exception = assertThrows(Example.class, () -> method.invoke(example));
0code> method, which will likely yield unexpected results for your users—and very likely a crashed application.

Checked versus Unchecked Java Exceptions

Java exceptions can be broken down into one of three categories:

  1. Checked - these are exceptions that are checked by the compiler at compile time. These exceptions must be caught by a try/catch in the code or noted as thrown by the method. For instance, if a program attempts to access a file that is currently unavailable, the method to access the file must either catch or throw a
    Example example = new Example();
    Method method = Example.class.getMethod("divide");
    Exception exception = assertThrows(Example.class, () -> method.invoke(example));
    2
  2. Error - errors are exceptions that happen externally to your Java program. One common example of the error is when the Java virtual machine (JVM) runs out of memory, which will throw an
    Example example = new Example();
    Method method = Example.class.getMethod("divide");
    Exception exception = assertThrows(Example.class, () -> method.invoke(example));
    3
  3. Runtime - runtime exceptions are internal to your application but are not typically recoverable. For example, an object that is expected to have a value but is actually null. In this case, a
    Example example = new Example();
    Method method = Example.class.getMethod("divide");
    Exception exception = assertThrows(Example.class, () -> method.invoke(example));
    4 exception would be thrown.

Often, these three categories are broken down into checked and unchecked classifications—error and runtime exceptions are grouped together as unchecked, which, per their name, are not checked at compile time and can result in runtime errors.

Now let’s walk through some of the most common Checked and Unchecked exceptions you’re likely to encounter in Java.

Checked Exceptions

Let's start by looking at some of the most common checked exceptions in Java.

1. ClassNotFoundException

The

Example example = new Example();
Method method = Example.class.getMethod("divide");
Exception exception = assertThrows(Example.class, () -> method.invoke(example));
5 happens when a required class cannot be found on the class path. The most common situation where the
Example example = new Example();
Method method = Example.class.getMethod("divide");
Exception exception = assertThrows(Example.class, () -> method.invoke(example));
5 occurs is when an external dependency is not available, which stems from application misconfiguration. In Maven-based projects, for example, this would translate to a missing or misconfigured
Example example = new Example();
Method method = Example.class.getMethod("divide");
Exception exception = assertThrows(Example.class, () -> method.invoke(example));
7.

The easiest way to reproduce this error is to simply delete a required .class file of a previously-running program. When the program attempts to make a call to a method inside the deleted .class file, it will throw the

Example example = new Example();
Method method = Example.class.getMethod("divide");
Exception exception = assertThrows(Example.class, () -> method.invoke(example));
5.

2. InvocationTargetException

The InvocationTargetException is related to the reflection functionality of Java and occurs when trying to invoke a method or constructor that results in throwing an exception. To illustrate, consider the following class:

public class Example {
  public int divide(int numerator) {
    return numerator / 0;
  }
}

The

Example example = new Example();
Method method = Example.class.getMethod("divide");
Exception exception = assertThrows(Example.class, () -> method.invoke(example));
9 method includes an input number (numerator), but the denominator is fixed at zero, which will produce a divide by zero error (ArithmeticException).

The

public class Example {
  public int divide(int numerator) {
    return numerator / 0;
  }

     public int addOne(int number) {
         return doSomethingPrivate(number);
     }

     private int doSomethingPrivate(int number) {
         return number++;
     }
 }
0code> error occurs when using reflection to invoke the method:

Example example = new Example();
Method method = Example.class.getMethod("divide");
Exception exception = assertThrows(Example.class, () -> method.invoke(example));

Since the

public class Example {
  public int divide(int numerator) {
    return numerator / 0;
  }

     public int addOne(int number) {
         return doSomethingPrivate(number);
     }

     private int doSomethingPrivate(int number) {
         return number++;
     }
 }
0 is in the reflection layer, the ArithmeticException is wrapped inside this provided exception.

3. InterruptedException

Every thread has a boolean

public class Example {
  public int divide(int numerator) {
    return numerator / 0;
  }

     public int addOne(int number) {
         return doSomethingPrivate(number);
     }

     private int doSomethingPrivate(int number) {
         return number++;
     }
 }
2 property used as an internal flag representing its interrupted status. This property provides a way for threads to interrupt—or stop—other threads/tasks.

The

public class Example {
  public int divide(int numerator) {
    return numerator / 0;
  }

     public int addOne(int number) {
         return doSomethingPrivate(number);
     }

     private int doSomethingPrivate(int number) {
         return number++;
     }
 }
3 is thrown when a thread that is working or sleeping is interrupted. Throwing/catching this exception allows your code to know if and when a thread has been stopped.

4. NoSuchMethodException

Like the

public class Example {
  public int divide(int numerator) {
    return numerator / 0;
  }

     public int addOne(int number) {
         return doSomethingPrivate(number);
     }

     private int doSomethingPrivate(int number) {
         return number++;
     }
 }
0 (above), the
public class Example {
  public int divide(int numerator) {
    return numerator / 0;
  }

     public int addOne(int number) {
         return doSomethingPrivate(number);
     }

     private int doSomethingPrivate(int number) {
         return number++;
     }
 }
5 is related to the use of reflection. This error stems from trying to access a provided method name that either does not exist or is configured as a private method. Consider the simple example below:

public class Example {
  public int divide(int numerator) {
    return numerator / 0;
  }

     public int addOne(int number) {
         return doSomethingPrivate(number);
     }

     private int doSomethingPrivate(int number) {
         return number++;
     }
 }

The

public class Example {
  public int divide(int numerator) {
    return numerator / 0;
  }

     public int addOne(int number) {
         return doSomethingPrivate(number);
     }

     private int doSomethingPrivate(int number) {
         return number++;
     }
 }
6 method is a private method and not visible in the following scenario:

Class c = Class.forName("Example");
Method method = c.getDeclaredMethod("doSomethingPrivate", parameterTypes);
method.invoke(objectToInvokeOn, params);

As a result, it throws a

public class Example {
  public int divide(int numerator) {
    return numerator / 0;
  }

     public int addOne(int number) {
         return doSomethingPrivate(number);
     }

     private int doSomethingPrivate(int number) {
         return number++;
     }
 }
5.

Unchecked Exceptions

Now let's look at some of the most common Unchecked exceptions in Java.

1. NullPointerException

A

Example example = new Example();
Method method = Example.class.getMethod("divide");
Exception exception = assertThrows(Example.class, () -> method.invoke(example));
4 is thrown when a Java program attempts to process an object which contains a null value.

public class Example {
  public void doSomething() {
    Integer number = null;

    if (number > 0) {
      System.out.println("Positive number");
    }
  }
}


In the example above, the number (Integer) object is null, so performing a simple evaluation will throw a

Example example = new Example();
Method method = Example.class.getMethod("divide");
Exception exception = assertThrows(Example.class, () -> method.invoke(example));
4.

2. ArrayIndexOutOfBoundsException

The

Class c = Class.forName("Example");
Method method = c.getDeclaredMethod("doSomethingPrivate", parameterTypes);
method.invoke(objectToInvokeOn, params);
0 occurs while processing an array and asking for a position that does not exist within the size of the array. Consider the following example:

public class Example {
  public void processArray() {
    List names = new ArrayList<>();
    names.add("Eric");
    names.add("Sydney");

    return names.get(5);
  }
}

The

Class c = Class.forName("Example");
Method method = c.getDeclaredMethod("doSomethingPrivate", parameterTypes);
method.invoke(objectToInvokeOn, params);
1 list contains two values, so 1 is the valid max index of this zero-based structure. As a result, asking for the name at position 5 will return an
Class c = Class.forName("Example");
Method method = c.getDeclaredMethod("doSomethingPrivate", parameterTypes);
method.invoke(objectToInvokeOn, params);
0.

3. IllegalStateException

The

Class c = Class.forName("Example");
Method method = c.getDeclaredMethod("doSomethingPrivate", parameterTypes);
method.invoke(objectToInvokeOn, params);
3 is thrown when a method is being called at an illegal or inappropriate time. A common occurrence of this exception is thrown when attempting to remove an item from the list while you are processing that list, as demonstrated below:

public class Example {
  public void processArray() {
    List names = new ArrayList<>();
    names.add("Eric");
    names.add("Sydney");

    Iterator iterator = names.iterator();

    while (iterator.hasNext()) {
      iterator.remove();
    }
  }
}

In the example above, calling the

Class c = Class.forName("Example");
Method method = c.getDeclaredMethod("doSomethingPrivate", parameterTypes);
method.invoke(objectToInvokeOn, params);
4 method inside the while loop will throw an
Class c = Class.forName("Example");
Method method = c.getDeclaredMethod("doSomethingPrivate", parameterTypes);
method.invoke(objectToInvokeOn, params);
3.

4. ClassCastException

The

Class c = Class.forName("Example");
Method method = c.getDeclaredMethod("doSomethingPrivate", parameterTypes);
method.invoke(objectToInvokeOn, params);
6 is thrown when you attempt to cast one object into another object that is not a member of the class hierarchy. This could be as simple as trying to cast a Long object to a String object as shown below:

public class Example {
  public void incorrectCastExample() {
    Long value = 1967L;
    String name = (String) value;
  }
}

5. ArithmeticException

The

Class c = Class.forName("Example");
Method method = c.getDeclaredMethod("doSomethingPrivate", parameterTypes);
method.invoke(objectToInvokeOn, params);
7 occurs when an exceptional arithmetic condition has occurred. For example, this type of exception often happens when a program attempts to divide by zero, which was first illustrated in the InvocationTargetException section (above):

return numerator / 0;

Dividing by zero is not a valid mathematical operation, which throws an

Class c = Class.forName("Example");
Method method = c.getDeclaredMethod("doSomethingPrivate", parameterTypes);
method.invoke(objectToInvokeOn, params);
7 in Java.

6. IllegalArgumentException

The

Class c = Class.forName("Example");
Method method = c.getDeclaredMethod("doSomethingPrivate", parameterTypes);
method.invoke(objectToInvokeOn, params);
9 is often used to capture errors when a provided method value does not meet expectations. To illustrate, consider an example where a date is requested and cannot be in the future:

public class Example {
   public void validDate(LocalDate localDate) throws IllegalArgumentException {
     if (localDate.after(LocalDate.now())) {
       throw IllegalArgumentException("localDate=" + localDate + " cannot be in the future");
     }
   }
   }

While a future date is a valid value for the date-based object, the business rules for this instance requires the object to not be in the future.

 

Rollbar and Debugging Java Errors

Rollbar provides a different approach to Java exception handling and analysis. It's focused on not only agile development and continuous delivery, but on providing real-time visibility into your application without having to refresh cluttered log screens and mine mountains of data.

Furthermore, the data that arrives into the Rollbar dashboard not only delivers on the metrics expected by production support and DevOps teams, but also links to the underlying source code — even to the point where existing tickets can link to an unexpected event ... or creating a new ticket directly from Rollbar itself.

Unlike traditional monitoring solutions, Rollbar focuses directly on the errors in the code—providing a continuous code improvement platform that helps developers proactively discover, predict, and remediate errors faster—before users report issues.

 

Track, Analyze and Manage Errors With Rollbar

![Rollbar in action](https://rollbar.com/wp-content/uploads/2022/04/[email protected])

Managing errors and exceptions in your code is challenging. It can make deploying production code an unnerving experience. Being able to track, analyze, and manage errors in real-time can help you to proceed with more confidence. Rollbar automates error monitoring and triaging, making fixing errors easier than ever. Try it today.

What are the 3 types of exceptions?

There are three types of exception—the checked exception, the error and the runtime exception.

What are the two types of exceptions?

There are mainly two types of exceptions: checked and unchecked. An error is considered as the unchecked exception.

What are the different exceptions?

Common checked exceptions include IOException, DataAccessException, InterruptedException, etc. Common unchecked exceptions include ArithmeticException, InvalidClassException, NullPointerException, etc. 6. These exceptions are propagated using the throws keyword.

Where are exceptions used in Java?

The classic definition of an exception is an event that occurs during the execution of a program and that disrupts the normal flow of instructions. Java exceptions are specialized events that indicate something bad has happened in the application, and the application either needs to recover or exit.