What is Checked Exception in java

All exception or the classes that extend Throwable class except RuntimException or error are known as checked exception.

Examples of CheckedExceptions:-

  1. ClassNotFoundException
  2. NoSuchFieldException
  3. IllegalAccessException
  4. EoFException …etc  

Thought Example

import java.io.*;

class DemoCheckedException {  

   public static void main(String args[]) 

   {

FileInputStream fis = null;

/*This constructor FileInputStream(File filename)

 * throws FileNotFoundException which is a checked

 * exception*/

        fis = new FileInputStream(“B:/myfile.txt”); 

int m; 

/*Method read() of FileInputStream class also throws 

 * a checked exception: IOException*/

while(( m = fis.read() ) != -1) 

System.out.print((char)m); 

     /*The method close() closes the file input stream

 * It throws IOException*/

fis.close(); 

   }

}



Result: Output of program is :

Exception in thread “main” java.lang.Error: Unresolved compilation problems: 

Unhandled exception type FileNotFoundException

Unhandled exception type IOException

Unhandled exception type IOException

Post a Comment

Previous Post Next Post