Checked and Unchecked Exception in Java – Examples and Differences

In our previous article, we have already discussed Java Exceptions. In that article, we covered the two types of exceptions  which are Checked and Unchecked Exception in Java.

In this article, we will discuss the difference between both of them along with the examples. Let’s start with a detailed discussion on each of them separately.

What are Checked Exceptions in Java?

The exceptions that are checked during the compile-time are termed as Checked exceptions in Java. The Java compiler checks the checked exceptions during compilation to verify that a method that is throwing an exception contains the code to handle the exception with the try-catch block or not.

And, if there is no code to handle them, then the compiler checks whether the method is declared using the throws keyword. And, if the compiler finds neither of the two cases, then it gives a compilation error. A checked exception extends the Exception class.

Examples of Java Checked Exceptions

For example, if we write a program to read data from a file using a FileReader class and if the file does not exist, then there is a FileNotFoundException.

Some checked Exceptions are

  • SQLException
  • IOException
  • ClassNotFoundException
  • InvocationTargetException
  • FileNotfound Exception

Code to illustrate the checked exception:

package com.techvidvan.exceptions;
import java.io.File;
import java.io.FileReader;
public class CheckedExceptions
{
  public static void main(String args[])
  {
    File file = new File("/home/techvidvan/file.txt");
    FileReader fileReader = new FileReader(file);
    System.out.println("Successful");
  }
}

Output:

Exception in thread “main” java.lang.Error: Unresolved compilation problem:
Unhandled exception type FileNotFoundException
at project1/com.techvidvan.exceptions.CheckedExceptions.main(CheckedExceptions.java:10)

Now, if we use the throws keyword with the main then we will not get any error:

package com.techvidvan.exceptions;
import java.io.*;
public class CheckedExceptions
{
  public static void main(String args[]) throws IOException
  {
    File file = new File("/home/techvidvan/file.txt");
    FileReader fileReader = new FileReader(file);
    System.out.println("Successful");
  }
}

Output:

Successful

We can also fix the code using the try-catch block:

import java.io.*;
public class Example
{
  public static void main(String args[])
  {
    FileInputStream fis = null;
    try
    {
      fis = new FileInputStream("/home/techvidvan/file.txt");
    }catch(FileNotFoundException fnfe)
    {
      System.out.println("The specified file is not " +
          "present at the given path");
    }
    int k;
    try
    {
      while(( k = fis.read() ) != -1)
      {
        System.out.print((char)k);
      }
      fis.close();
    }catch(IOException ioe)
    {
      System.out.println("I/O error occurred: "+ioe);
    }
  }
}

Output:

The specified file is not present at the given path
Exception in thread “main” java.lang.NullPointerException
at project1/com.techvidvan.exceptions.Example.main(Example.java:15)

What are Java Unchecked Exceptions?

An exception that occurs during the execution of a program is called an unchecked or a runtime exception. The main cause of unchecked exceptions is mostly due to programming errors like attempting to access an element with an invalid index, calling the method with illegal arguments, etc.

In Java, the direct parent class of Unchecked Exception RuntimeException.

Unlike the checked exceptions, the compiler generally ignores the unchecked exceptions during compilation. Unchecked exceptions are checked during the runtime. Therefore, the compiler does not check whether the user program contains the code to handle them or not.

Examples of Unchecked Exceptions in Java

For example, if a program attempts to divide a number by zero. Or, when there is an illegal arithmetic operation, this impossible event generates a runtime exception.

Suppose, we declare an array of size 10 in a program, and try to access the 12th element of the array, or with a negative index like -5, then we get an ArrayIndexOutOfBounds exception.

Some unchecked exceptions are

  1. ArithmeticException
  2. NullPointerException
  3. ArrayIndexOutOfBoundsException
  4. NumberFormatException
  5. InputMismatchException
  6. IllegalStateException
  7. Missing Resource Exception
  8. No Such Element Exception
  9. Undeclared Throwable Exception
  10. Empty Stack Exception

Code to illustrate the Unchecked Exception:

package com.techvidvan.exceptions;
public class UnCheckedExceptions
{
  public static void main(String args[])
  {
    //ArrayIndexOutOfBoundsException
    int array[] = {1, 2, 3, 4, 5};
    System.out.println(array[7]);

  }
}

Output:

Exception in thread “main” java.lang.ArrayIndexOutOfBoundsException: Index 7 out of bounds for length 5
at project1/com.techvidvan.exceptions.UnCheckedExceptions.main(UnCheckedExceptions.java:8)

Note: Though the compiler does not check these exceptions, it doesn’t mean that we shouldn’t handle them. In fact, we should handle them more carefully to provide a safe exit.

Comparison between Checked Exceptions and Java Unchecked Exception in Java

S.N. Checked Exception Unchecked Exception
1 Checked exceptions occur at compile time. Unchecked exceptions occur at runtime.
2 Also called Compile-time exceptions Also called Run-time exceptions
3 The compiler checks a checked exception. The compiler ignores the unchecked exceptions.
4 We can handle these types of exceptions during compilation. We cannot catch or handle these exceptions during the compilation because they are generated by the mistakes in the program.
5 The compiler will give an error if the code does not handle the checked exceptions. The compiler will never give an error if the code does not handle the unchecked exceptions.
6 They are the direct subclass of the Exception class. They are runtime exceptions and hence are not a part of the Exception class and are the subclass of RuntimeException class
7 JVM needs to catch and handle the checked exception. JVM needs not catch and handle the unchecked exception.
8 Checked Exceptions mainly occur when the chances of failure are too high. Unchecked Exceptions mainly occur due to programming mistakes.
9 We can create user-defined checked exceptions by extending java.Lang.Exception class We can create user-defined Unchecked exceptions by extending RuntimeException class
10 Examples of Checked exceptions:

File Not Found Exception

No Such Field Exception

SQL Exception

IO Exception

Interrupted Exception

No Such Method Exception

Class Not Found Exception

Examples of Unchecked Exceptions:

Array Index Out of Bounds Exception

NumberFormatException

InputMismatchException 

IllegalStateException

Arithmetic Exception

Null Pointer Exception

Security Exception

Exception Hierarchy

Java Exceptions are broadly divided into two parts: checked exceptions and unchecked exceptions. The following figure shows this Exception hierarchy in Java.

exception hierarchy in java

When to use Checked and Unchecked Exception in java

According to the Oracle Java Documentation, there is a guide on when to use checked exceptions and unchecked exceptions:

“If a client can reasonably be expected to recover from an exception, make it a checked exception. If a client cannot do anything to recover from the exception, make it an unchecked exception.”

For example, we can first validate the input file name before opening the file. And if we provide the invalid name of the input, then we can throw the checked exception.

The below code snippet shows this:

if (!isCorrectFileName(fileName))
{
       throw new IncorrectFileNameException("File name is invalid: " + fileName );
}

If the input file name is an empty string, it means there is an error in the code. In this case, we should throw an unchecked exception.

The below code snippet shows this:

if (fileName == null || fileName.isEmpty())
{
       throw new NullOrEmptyException("The filename is null or empty.");
}

Summary

Exceptions in Java may hinder the normal execution of a program. There are two kinds of exceptions in Java which are Checked or compile-time exceptions and Unchecked or runtime exceptions. In checked exceptions, we have to write the code to handle them otherwise the compiler gives an error.

And, in runtime exceptions, it is not necessary to write the code to handle the exception and still, the compiler does not give any error. This article gave you the detailed points of differences between both these exceptions in Java. You might have understood when to use either of two exceptions.