Difference Between Checked and Unchecked Exception with Examples

Difference between Checked Exception and Unchecked Exception is one of the most basic and frequently asked question in any java developer interview, irrespective of the experience an interviewee holds. In this article I will be sharing what is Exception, Checked Exception and Unchecked Exception, differences between Checked and Unchecked exception , similarities between them and examples.

Exception: Any change in the regular course of execution of a program that causes the program to pause or stop is called an exception.

What is Checked and Unchecked Exception


checked and unchecked exception in java


Checked Exception: Any exception that is checked by the compiler during compile time is called as Checked Exception. Checked exception are the classes which inherit Throwable class except RuntimeException and Error.
For example IOException and FileNotFoundException etc.

Unchecked Exception: Unchecked exceptions are the classes which inherit RuntimeException and Error. They are not checked by the compiler at compile time instead they are checked at runtime.
For example NullPointerException, ArithmeticException etc.

Difference between Checked Exception and Unchecked Exception in Java 


1. Compile time checking : The most basic difference between checked and unchecked exceptions is the compile time checking. Checked exceptions are checked by compiler during compile time and Unchecked exceptions are not checked by the compiler instead checked at the run time.

2. Exception class and hierarchy: Checked exceptions are sub-classes of java.lang.Exception and not a sub class of runtime exception and error i.e., java.lang.RuntimeException, java.lang.Error.
All Unchecked exceptions are sub-classes of java.lang.RuntimeException and java.lang.Error.

java exception handling hierarchy


3. Methods to handle exception: Checked exceptions must be handled using the try-catch block or throws keyword.
Unchecked exceptions do not cause any harm if not handled as they do not stop compilation of code and generally a bad practice.

4. Examples:
Checked exception – FileNotFoundException, SQLException, IOException
Unchecked Exception – ArithmeticException, ArrayIndexOutOfBoundException, NoClassDefFoundException

Examples of Checked and Unchecked Exception

Checked Exception Example :


In the below example we are just providing the path and name of the file using FileInputStream. Since there is no file with such name in the given location, compiler will throw FileNotFoundException.

import java.io.*;

public class CheckedExceptionExample {
public static void main(String[] args)
 {
   FileInputStream fileInput = null;
   /* FileInputStream(File filename) constructor 
      throws Checked exception i.e 
      FileNotFoundException */ 
   fileInput = new FileInputStream("C://unavailableDoc.txt"); 
  } 
}

Output :

/CheckedExceptionExample.java:13: error: unreported exception FileNotFoundException; must be caught or declared to be thrown
      fileInput = new FileInputStream("unavailableDoc.txt");


How to overcome above compilation error ?

There are two ways to handle above compilation error:

1. Using try/catch block
2. Using throws keyword


1. Using try/catch block

The best way to handle checked exception is to use try/catch block. Using throws keyword is not the best exception handling practice. Using try/catch block you can make handling the exception more meaningful and easy to understand. After adding try/catch block, the below code will compile fine.


import java.io.*;

public class CheckedExceptionExample {
public static void main(String[] args)
{
   FileInputStream fileInput = null;
   try
   { 
       /* FileInputStream(File filename) constructor 
         throws Checked exception i.e 
         FileNotFoundException */ 
       fileInput = new FileInputStream("C://unavailableDoc.txt");
   
   catch(FileNotFoundException e)
   {
      System.out.println("File is not found in the provided location : " + e);
   }
 }
}


Output :
File is not found in the provided location : java.io.FileNotFoundException: unavailableDoc.txt (No such file or directory)

Since the name of the exception i.e FileNotFoundException is sufficient to tell the root cause in the above example. But in the real world code, where you have to deal with custom exceptions then try/catch block becomes very helpful.

2. Using throws keyword

You can also handle the exception using throws keyword. But it is not the best practice. Using throws keyword is like passing exception to caller method to let it handle. If an exception is not handled in the application, then it will propogate to the JVM. As a result, JVM may terminate the program. After adding throws keyword,  below code will compile fine.

import java.io.*;

public class CheckedExceptionExample {
public static void main(String[] args) throws FileNotFoundException 
 {
   FileInputStream fileInput = null;
   fileInput = new FileInputStream("C://unavailableDoc.txt"); 
  } 
}

Output :
Exception in thread "main" java.io.FileNotFoundException: C:/unavailableDoc.txt (No such file or directory)

Unchecked Exception Example :

Unchecked exceptions do not get checked at compile-time. For example, if your program will throw an unchecked exception but you do not handle the exception (i.e there is no throws keyword and try-catch block in the code), it will not give compilation error.

import java.io.*;

public class UncheckedExceptionExample
{ 
 /* Below method does not have throws keyword
    and try-catch block , but it will compile */  
 public static void main(String []args){ 
        int num1=100; 
        int zero=0;  
        /* Dividing any number by 0 
         will give Arithmetic Exception*/ 
        int output=num1/zero;
        System.out.println("Output : "+ output);       
  }
}

Output :
Exception in thread "main" java.lang.ArithmeticException: / by zero
    at UncheckedExceptionExample.main(UncheckedExceptionExample.java:18)

Similarities between Checked and Unchecked Exception:

1. Both of them are sub classes of Throwable class.

2. Both can be handled by try-catch blocks.

3. Functionally both are the same but unchecked exceptions are not considered best practices.

Recap : Difference between Checked and Unchecked Exception




Checked ExceptionUnchecked Exception
Compile time checkingYesNo
Class HierarchyAll subclasses of Exception except subclasses of java.lang.Runtime exception
and java.lang.Error are checked exceptions
All subclasses of java.lang.RuntimeException and java.lang.Error are unchecked exceptions
Handling of exceptionMust be handled by either using try/catch block or throws keywordNot necessary to handle
ExamplesSQLException, IOException, FileNotFoundExceptionArithmeticException, ArrayIndexOutOfBoundException, NoClassDefFoundException


Please let me know in comments in case you have any questions or doubts regarding difference between checked and unchecked exceptions in java.

References :
Oracle doc

About The Author

Subham Mittal has worked in Oracle for 3 years.
Enjoyed this post? Never miss out on future posts by subscribing JavaHungry