Blog |

Most Common Java Exceptions

Most Common Java Exceptions
Table of Contents

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:

Java exceptions stack trace

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 main 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 maincode> 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 FileNotFoundException.
  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 OutOfMemoryError.
  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 NullPointerException 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 ClassNotFoundException happens when a required class cannot be found on the class path. The most common situation where the ClassNotFoundException 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 <---dependency--->.

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 ClassNotFoundException.

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 divide() method includes an input number (numerator), but the denominator is fixed at zero, which will produce a divide by zero error (ArithmeticException).

The InvocationTargetExceptioncode> 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 InvocationTargetException is in the reflection layer, the ArithmeticException is wrapped inside this provided exception.

3. InterruptedException

Every thread has a boolean interrupt 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 InterruptedException 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 InvocationTargetException (above), the NoSuchMethodException 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 doSomethingPrivate() 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 NoSuchMethodException.

Unchecked Exceptions

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

1. NullPointerException

A NullPointerException 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 NullPointerException.

2. ArrayIndexOutOfBoundsException

The ArrayIndexOutOfBoundsException 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 names 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 ArrayIndexOutOfBoundsException.

3. IllegalStateException

The IllegalStateException 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 remove() method inside the while loop will throw an IllegalStateException.

4. ClassCastException

The ClassCastException 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 ArithmeticException 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 ArithmeticException in Java.

6. IllegalArgumentException

The IllegalArgumentException 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.

Related Resources

"Rollbar allows us to go from alerting to impact analysis and resolution in a matter of minutes. Without it we would be flying blind."

Error Monitoring

Start continuously improving your code today.

Get Started Shape