Home

 › 

Articles

 › 

3 Types of Exceptions in Java Explained in Plain English

OOPs in Java

3 Types of Exceptions in Java Explained in Plain English

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.

Exceptions in Java
Checking the classpath could be a way to resolve this checked exception.

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

Exception in Java
Resolve this exception by increasing the size of the array or changing the element you’re trying to access.

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

Exceptions in Java
If an exception can’t be handled with Java’s built-in functions, just create an exception and define it yourself.

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

Exceptions in Java
Errors like this StackOverFlowError are more serious than exceptions and are not recoverable.

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

Frequently Asked Questions

What are exceptions?

Exceptions occur during execution and interrupt the flow of a program. They indicate that a problem has occurred that compromises the running of a program.

 

 

 

 

 

 

What is exception handling?

Exception handling works to handle errors and unexpected behavior so that programs can work correctly.

How are exceptions handled in Java?

We handle exceptions mostly by using try-catch blocks, where we throw an exception and catch it. The code within this block will be executed to handle the exception. If no code is found, then the exception moves up the call stack until it’s dealt with or the program’s terminated. The finally block can also be used after a catch block to designate code that must be executed regardless of whether the exception is resolved or not.

What are the main types of exceptions?

There are 4 main types of Java exceptions. These are checked, unchecked, user-defined exceptions and errors.

What's the difference between checked and unchecked exceptions?

Checked exceptions occur at compile time and must be handled, but unchecked exceptions occur during runtime and don’t need to be declared in a method’s signature.

What is a user-defined exception?

These can also be called custom exceptions, which are defined by the user. These are usually used to deal with error conditions that can’t be handled by the built-in exceptions. To create these, the exception class must be extended.

What's the difference between an exception and an error?

Exceptions occur during execution, but errors are irrecoverable and can’t be handled.

When should you use each type of exception?

Checked exceptions are used when an error can be recovered. Unchecked exceptions should be used when we can’t expect o recover from an error. You should use user-defined exceptions when the built-in functions can’t handle the problem.

To top