Difference between Checked vs Unchecked Exceptions in Java

UPDATED: 20 May 2015
Checked Exception and Unchecked Exception

Checked Exception
When there is possible chances of Failure Checked Exceptions are Introduced. Checked Exceptions are the one checked at compile time by Java. Checked Exceptions must be caught within try-catch block or throw that exception in its definition using throws keyword.

Any Exception that is direct sub-class of Exception but doesn't inherit java.lang.RuntimeException are Checked Exception.


Example of Checked Exception
You want to read any file on system using FileReader, So there is chances of File not found on specified path this is called Checked Exception(Possible chances of Failure).
import java.io.*;

public class CheckedException {

   public static void main(String[] args) {
 /* Create object of File by providing absolute path */
 File objFile = new File("D:\\myfile.txt");
 BufferedReader objBufferedReader = null;
 FileReader objFileReader = null;
 try {
    /* Get FileReader on File */
    objFileReader = new FileReader(objFile);
    /* Get BufferedReader from FileReader */
    objBufferedReader = new BufferedReader(objFileReader);
       String strFileline = "";
    /* Read file line by line */
    while((strFileline = objBufferedReader.readLine()) != null){
   System.out.println(strFileline);
    }
 } catch (FileNotFoundException e) {
    /* Checked Exception */
    e.printStackTrace();
 } catch (IOException e) {
    /* Checked Exception */
    e.printStackTrace();
 }finally{
    /* Close the resources used for file reading */
    try {
  if(objBufferedReader != null){
     objBufferedReader.close();
  }
  
  if(objFileReader != null){
     objBufferedReader.close();
  }
    } catch (IOException e) {
  e.printStackTrace();
    }
 }
   }
}

Unchecked Exception
Exception that are not checked by Java Compiler at compile time called Unchecked Exception. Any Exception that inherits java.lang.RuntimeException are UnChecked Exception.


Example of Unchecked Exception
Dividing two Integer numbers is best example of Unchecked Exception. You are getting two values after evaluation of your logic and not sure what will be the values and divide it, that leads to java.lang.ArithmeticException.
public class UnCheckedException {

   public static void main(String[] args) {
 int x = 10;
 int y = getY();
 System.out.println(x / y);
   }

   /**
    * This is example of getting value from some method call.
    * There is possibilities of getting value `0`.
    *  
    * Java compiler can't identify such errors
    */
   public static int getY(){
 return 2-2;
   }
}

0 comments :