Common exception types in java

Java Errors & Exception Handling Tutorial

In this Java tutorial we learn about the different errors our application can generate, known as exceptions.

We learn about compile-time and runtime exceptions, and out-of-our-control type errors and how to handle them with the try..catch..finally statements.

We also discuss how to customize errors with the throw keyword and some common exception types.

What are exceptions

Exceptions (exceptional events) occur when the normal flow of a program is disrupted and the application terminates in an abnormal way.

Exceptions can occur for different reasons. Some are caused by users, others are caused by programmers, some may even be caused by external resources that fail in some way.

Based on the reasons above, we have three exception categories.

1. Checked exceptions, otherwise known as compile-time exceptions.

These exceptions occur when the program actively checks for exceptions at compilation time.

2. Unchecked exceptions, otherwise known as runtime exceptions.

These exceptions include bugs in the code, such as logic errors.

These are technically not exceptions, but rather problems that arise and are beyond the control of both the user and the programmer.

For example, when a network is not available to connect to, or a stack overflow occurs.

What is exception handling

Exception handling is when a programmer actively checks for exceptions with whichever method the language provides.

To do this, Java provides us with the try..catch..finally construct and throw keyword.

How to handle an exception with try..catch in Java

The try and catch blocks will first try to execute a section of code with the try statement. If the code fails, the exception will be caught by the catch statement, and we can handle them in its code block.

    The type_of_exception is specific to what we want to check for and is used in to throw an exception.

We learn more about throwing exceptions further along in this lesson.

First, let’s raise a common error as an example.

   In the example above, we have an array with 4 elements. We then try to access the 5th element, which doesn’t exist, causing an ‘Array out of bounds’ error.
 Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 4

We can use the try..catch statements to catch this error and write code to handle it when it occurs.

     In the example above, we try to access the 5th element in the array in the try block. It still doesn’t exist and will raise an error, except this time the error isn’t handled by the compiler, but by the code we wrote in the catch statement.

The finally statement in Java

The finally statement will execute its code after the try..catch, regardless if an error was caught or not.

Источник

Most Common Java Exceptions

Most Common Java 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:

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 main code> 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 .

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:

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 InvocationTargetException code> 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.

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() < Listnames = 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() < Listnames = 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:

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):

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:

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/section-1-real-time-errors@2x-1-300×202.png)

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.

Источник

Читайте также:  Blend pass through css
Оцените статью