Sunday, 6 October 2019

Java Tutorials | Checked vs Unchecked Exceptions in Java


In Java, there are two types of exceptions:
1) Checked Exceptions are the exceptions that are checked at compile time. If some code in a method throws a checked exception, the method must either handle the exception or propagate the exception using throws keyword.

For example, below given Java program that opens the file at location “/Users/rajesh.dixit/Desktop” and prints it. The program doesn’t compile as the function main() uses FileReader() and FileReader() throws a checked exception FileNotFoundException. It also uses readLine() and close() methods, and these methods also throw checked exception IOException

import java.io.BufferedReader;
import java.io.FileReader;
public class CheckedException {
      public static void main(String[] args) {
            FileReader file = new FileReader("/Users/rajesh.dixit/Desktop/file.txt");
            BufferedReader fileInput = new BufferedReader(file);
            // Print first 3 lines of file "C:\test\a.txt"
            for (int i = 0; i < 5; i++) {
                  System.out.println(fileInput.readLine());
            }
            fileInput.close();
      }
}
Output:
Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - unreported exception java.io.FileNotFoundException; must be caught or declared to be thrown at CheckedException.main(CheckedException.java:5)

To fix the above program, we either need to specify a list of exceptions using throws or need to use a try-catch block. In below-given code, we have used throws in the below program. Since FileNotFoundException is a subclass of IOException, just specifying IOException in the throws list and make the above program compiler-error-free.

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class CheckedException {
     public static void main(String[] args) throws IOException {
          FileReader file = new FileReader("/Users/rajesh.dixit/Desktop/file.txt");
          BufferedReader fileInput = new BufferedReader(file);

          // Print first 3 lines of file "C:\test\a.txt"
          for (int i = 0; i < 5; i++) {
               System.out.println(fileInput.readLine());
          }

          fileInput.close();
     }
}
Output:
First three lines of file /Users/rajesh.dixit/Desktop/file.txt

2) Unchecked are the exceptions that are not checked at the compiled time. In C++, all exceptions are unchecked, so it is not forced by the compiler to either handle or specify the exception. It is up to the programmers to be civilized, and specify or catch the exceptions. In Java exceptions under Error and RuntimeException classes are unchecked exceptions, everything else under throwable is checked.

Below given program compiles successfully but it throws ArithmeticException at run time. The compiler allows it to compile as ArithmeticException is an unchecked exception.

public class UncheckedException {
      public static void main(String args[]) {
            int x = 0;
            int y = 10;
            int z = y / x;

            System.out.println(z);
      }
}
Output:
Exception in thread "main" java.lang.ArithmeticException: / by zero
      at UncheckedException.main(UncheckedException.java:5)

Should we make our exceptions checked or unchecked?
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

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...