Checked vs Unchecked Exceptions


In Java, there are two types of exceptions: checked and unchecked exceptions.

Checked Exceptions
Checked exceptions are the exceptions that are checked at compile time. If some code within a method throws a checked exception, then the method must either handle the exception or it must specify the exception using throws keyword. For example, consider the following Java program that opens the file none.txt and prints the first three lines of it. The program doesn’t compile, because 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.

CheckedException.java (checked exception)
import java.io.*; 
class CheckedException { 
  public static void main( String[ ] args ) { 
    FileReader file = new FileReader( "none.txt" ); 
    BufferedReader fileInput = new BufferedReader( file ); 
    // Print first 3 lines of file "none.txt". 
    for ( int counter = 0; counter < 3; counter++ ) 
      System.out.println( fileInput.readLine( ) );  
    fileInput.close( ); 
  }
}
shell> javac CheckedException          

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

ThrowsException.java (throwing exception)
import java.io.*; 
class ThrowsException { 
  public static void main( String[ ] args ) throws IOException { 
    FileReader file = new FileReader( args[0] ); 
    BufferedReader fileInput = new BufferedReader( file ); 
    // Print the first 3 lines of file args[0]. 
    for ( int counter = 0; counter < 3; counter++ )
      System.out.println( fileInput.readLine( ) ); 
    fileInput.close( ); 
  }
}
shell> java ThrowsException            




      Whether it’s the best of times or the worst of times,    
      it’s the only time we’ve got.