Difference Between Checked and Unchecked Exceptions in Java

1. Objective

In our last tutorial, we studied the exception handling in java with examples. In this Java tutorial, we are going to learn checked exception in Java Programming Language, what is Java unchecked exception and how to handle the unchecked exception in Java. Moreover, we will discuss the difference between checked and unchecked exceptions in Java with an example program. At last, discuss user-defined exceptions in Java with syntax and example.
So, let’s start Checked and Unchecked Exceptions in Java.

Checked and Unchecked Exceptions in Java

Difference Between Checked and Unchecked Exceptions in Java

2. Checked and Unchecked Exceptions in Java

There are basically two types of exceptions in Java –

  • Checked Exception in Java
  • Unchecked Exception in Java

Let us study Checked and Unchecked Exceptions in Java in detail with examples.

Read about Java Exception in detail 

3. Checked Exceptions in Java

Checked Exceptions in Java are the special cases that are checked at compile time. In the event that some code inside a technique tosses a checked exemption, at that point the strategy should either handle the special case or it must indicate the special case utilizing throws keyword.

For instance, consider the accompanying Java program that opens document at locatiobn “C:\test\a.txt” and prints initial three lines of it. The program doesn’t compile, as the capacity Function main() utilizes FileReader() and FileReader() throws a checked exemption FileNotFoundException.

It likewise utilizes readLine() and close() techniques, and these strategies additionally throw checked special case IOException.

Let’s know about What is Multi Threading in Java

a. Example of Checked Exceptions in Java 

import java.io.*;
class Main
  {
    public static void main(String[] args)
      {
          FileReader file = new FileReader("C:\\test\\a.txt");
          BufferedReader fileInput = new BufferedReader(file);
          for (int counter = 0; counter < 3; counter++)
          System.out.println(fileInput.readLine());
          fileInput.close();
      }
 }

We either need to determine rundown of exceptions utilizing throws. We have utilized throws in the underneath program. Since FileNotFoundException is a subclass of IOException, we can simply indicate IOException in the throws rundown and make the above program compiler-error free.

Example –

import java.io.*;
class Main
  {
     public static void main(String[] args) throws IOException
       {
           FileReader file = new FileReader("C:\\test\\a.txt");
            BufferedReader fileInput = new BufferedReader(file);     
            // Print first 3 lines of file "C:\test\a.txt"
            for (int counter = 0; counter < 3; counter++)
            System.out.println(fileInput.readLine());      
           fileInput.close();
      }
 }

See also Data Structures in Java – Graph, Trie, Segment Tree & Suffix Tree

b. Handle Checked exception in Java using try-catch blocks

import java.io.*;
class Example
 { 
   public static void main(String args[])
      {
          FileInputStream fis = null;
          try
             {
                fis = new FileInputStream("B:/myfile.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);
                  }
            }
     }

Note –
Some of the examples are

  • SQLException
  • IOException
  • ClassNotFoundException
  • InvocationTargetException

4. Java Unchecked Exceptions

Java Unchecked exceptions are the exceptions that are not checked at an ordered time. In C++, all exceptions are unchecked. So, it isn’t constrained by the compiler to either handle or indicate the special case. It is up to the developers to acculturate, and indicate or catch the exemptions.

Do You Know Serialization and Deserialization in Java

In special cases under Error and RuntimeException classes are Java unchecked exceptions, everything else under throwable is checked.

Example 1 of Java Unchecked Exception –

class Example
  {
      public static void main(String args[])
         {
      int num1=10;
      int num2=0;
      int res=num1/num2;
      System.out.println(res);
          }
    }
//It will show exception while running
//ArithmeticException
//It is will not show at compile time

Example 2 of Java Unchecked Exception-

class Example
   {
      public static void main(String args[])
       {
    int arr[] ={1,2,3,4,5};
    //ArrayIndexOutOfBoundsException
    System.out.println(arr[7]);
       }
  }

 Note –
These are some Java unchecked exceptions.

  • NullPointerException
  • ArrayIndexOutOfBoundsException
  • ArithmeticException
  • IllegalArgumentException
  • NumberFormatException
Checked and Unchecked exceptions in Java

Checked and Unchecked Exceptions in Java

Let’s Explore Java File Class – java.io.File Class in Java

5. User-Defined Exceptions in Java

Till we study Checked and Unchecked Exceptions in Java with examples. Now, let’s talk about User-Defined Exception in Java Programming Language.
Exceptions can create by the user in Java, just by keeping the following points in mind –

  • An exception has to a child of throwable.
  • Exception class needs to extend if one wants a checked exception.
  • RunTime exception class needs to extend when we need a runtime exception.

Syntax of User-Defined Exception in Java–

class MyException extends Exception
{
}

Example of User-Defined Exception in Java–

import java.io.*;
public class InsufficientFundsException extends Exception
 {
     private double amount;
     public InsufficientFundsException(double amount)
      {
         this.amount = amount;
      }
        public double getAmount()
     {
        return amount;
     }
 }

So, this was all about the Difference between checked and unchecked exceptions in Java Tutorial. Hope you like our explanation.

Must read Method Overloading vs Overriding in Java

6. Conclusion

Hence, in this tutorial, we learned about the difference between checked and unchecked exceptions in Java with an example program and user-defined functions with example & syntax. Furthermore, if you have any query regarding checked and unchecked exceptions in Java, feel free to ask in the comment section.

Related Topic- Java Inner Class

For reference

Leave a Reply

Your email address will not be published. Required fields are marked *