As far as object oriented programming (OOP) languages go, Java is one of the most popular. The language has a vast standard library and is very versatile, as it can be run on any platform using the Virtual Machine. Sometimes, as with any programming project, you’re going to run into errors. In Java, these are handled through exceptions, of which there are many kinds. If you want to ensure your program will run smoothly and predictably, being familiar with exception handling is important. To this end, the rest of this article will detail what exceptions are and how they’re handled in Java, with examples to illustrate.
What Are Exceptions in Java?
Generally speaking, an exception is created when something undesirable happens during the runtime of a program. This often interrupts the expected flow of the execution, which is not what we want. Once an exception happens, an object is created which has details about the exception that can be useful for handling them. This is called an exception object, or exception for short.
Exceptions can happen for many reasons, but the most common are:
- Failure of a device
- Incorrect input from user
- Connection dropping out
- Running out of disk memory
- Trying to open an unavailable or corrupted file
- Errors in the code you’re trying to run
As such, the key purpose of exception handling is to get the program to flow normally again. There are three main types of exceptions — checked, unchecked, and user-defined. Let’s delve into these next.
Checked Exceptions
A checked exception in Java is one that must be dealt with by the programmer explicitly, usually done by using a try-catch block. The compiler checks whether these are handled at compile time. These can include SQLException, IOException, InterruptedException, or ClassNotFoundException. An explanation for these follows.
- SQLException: Where there are issues accessing the database.
- IOException: When an input/output error occurs, i.e. a file can’t be found.
- InterruptedException: When a sleeping thread is interrupted.
- ClassNotFoundException: The class trying to be accessed can’t be found.
As an example, look at this code:
import java.io.FileInputStream;
import java.io.FileNotFoundException;
public class FileReaderExample {
public static void main(String[] args) {
try {
FileInputStream fis = new FileInputStream("example.txt");
} catch (FileNotFoundException e) {
System.out.println("File not found: " + e.getMessage());
}
}
}
This code produces a runtime exception, specifically a ClassNotFoundException. The exception happens because the class “com.mycompany.exceptionhandling.Exceptionhandling” cannot be found, so checking the classpath could be a way to resolve this exception. You can see the results of trying to run this code in the image next.

©History-Computer.com
Unchecked Exceptions
In contrast to checked exceptions, unchecked exceptions in Java don’t need to be explicitly handled. Instead, these are thrown during the execution by the Java Virtual Machine (JVM), rather than at compile time. As such, they’re also known as runtime exceptions. Generally, these can occur at any point during runtime and are hard to predict. These include:
- ArithmeticException: Where an operation causes a problem, e.g. by trying to divide something by 0.
- NullPointerException: When a program tries to access an object reference through a null pointer.
- ClassCastException: Where an object is called for a class which it is not an instance of.
- IndexOutOfBoundsException: This occurs when we try to access a collection or array index that’s out of bounds.
Let’s illustrate an unchecked exception with the following example.
public class UncheckedExceptionExample {
public static void main(String[] args) {
int[] arr = new int[5];
System.out.println(arr[10]);
}
}
Here, we receive an IndexOutofBoundsException, since we’re trying to print the element at index 10. However, the array only has 5 elements, so we receive this exception. We could resolve this by either increasing the size of the array or changing the element we’re trying to access. We can see this demonstrated in the below image.

©History-Computer.com
User-Defined Exceptions
Sometimes, an exception can’t be handled with the built-in functions in Java. In these cases, you can create an exception and define it yourself, which is known as a user-defined exception. To demonstrate, we have this code:
public class CustomExceptionExample {
public static void main(String[] args) {
try {
throw new CustomException("This is a custom exception.");
} catch (CustomException e) {
System.out.println(e.getMessage());
}
}
}
We create a custom exception instance called “CustomException” and pass a string to the constructor. The exception is then thrown with the try block, and caught by the catch block. The exception message, “This is a custom exception,” is printed to the console. We can see this in the image below.

©History-Computer.com
What Keywords Are Used With Exceptions in Java?
There are some common keywords used when dealing with exceptions. These are:
- Try: This is used to designate a block where the exception code is to be placed. This must be used either with a catch block or finally block in tandem.
- Catch: This is used to handle an exception. It must have a try block before it, as it also can’t be used alone. A finally block can also be used after.
- Finally: This executes the code of the program, whether we’ve handled the exception or not.
- Throw: This is used to throw an exception, meaning an object with information about the exception is created, which is caught by a try-catch block, or the program is terminated. Basically, this “throws” an error message that we can examine to deal with the problem.
What Are Errors?
As you may suspect, errors are problems that occur during runtime. These are different from exceptions in Java. These could include:
- Memory running out (OutOfMemoryError)
- Memory leaking
- Library incompatibility
- Endless recursion
- Overflow errors (StackOverFlowError)
- Lack of method (NoSuchMethodError)
- When a class can’t be found (NoClassDefFoundError)
- When an interface can’t be found (LinkageError)
Typically, errors are more serious than exceptions and aren’t recoverable. This is what distinguishes them from exceptions. For example, the following code will produce a StackOverFlowError.
public class StackOverflowExample {
public static void main(String[] args) {
recursiveMethod(1);
}
public static void recursiveMethod(int i) {
System.out.println("Number: " + i);
recursiveMethod(i + 1);
}
}
We receive this error because the method “recursiveMethod” is called recursively without any stop point. We can see this in the image following. A new frame is added to the stack each time we call the method, which uses progressively more memory as it goes. The stack will eventually reach the maximum possible size, and we receive the error to show that we’ve run out of memory to be allocated. We could include an upper limit as a parameter to stop the recursion. Technically, errors are irrecoverable because they’re caused by a limit in the hardware, but can be resolved sometimes through such methods.

©History-Computer.com
Exceptions in Java: Wrapping Up
Being able to handle Java exceptions effectively is a crucial part of learning how to use the programming language. We need to deal with unexpected situations as best as possible so that programs work well. We can use built-in exception classes to deal with checked and unchecked exceptions or customize our own classes to deal with user-defined exceptions. The most common keywords to handle exceptions are the try, catch, and finally keywords. Overall, to have the most secure and reliable code possible, exception handling is a very useful concept.
The image featured at the top of this post is ©Wright Studio/Shutterstock.com.