Tutorials

Java Exception Handling


Checked Exception


Checked Exceptions are those exceptions which are detected by the compiler at compile time.

If compiler finds that your code snippet may throw exceptions such as resource not found, file not found, sql exception, etc., then it will not execute until and unless you fix this code.

 

Example

  • IOException
  • FileNotFoundException
  • SQLException

How to handle Checked Exception?

  1. try/catch→ Enclose the code that might throw compile time exception
  2. throws→  declare the exception at method level using throws

Example: A sample code which throws checked exception (detected at compile time)


import java.io.*;

class MyFileReader {

    public static void main(String[] args) {


        FileReader file = new FileReader("D:\\JavaFiles\\myFile.txt");
        BufferedReader fileInput = new BufferedReader(file);
         
        // Print first 4 lines of file "C:\test\a.txt"
        for (int counter = 0; counter < 4; counter++)

            System.out.println(fileInput.readLine());
        
            fileInput.close();

    }

}

OUTPUT:

Compiler error

 

Why compiler detects exception?

The above code snippet will detect and throw compile time error.

 

Reason being the presence of FileReader which throws Checked Exception FileNotFoundException and readLine & close which throws checked exception IOException.

 

In order save your code from compile time error:

  • enclose the code within try/catch block or
  • declare all Exceptions that could possibly occur using throws as shown below:

 public static void main(String[] args) throws IOException


 

Since FileNotFoundException is the child (sub class) of IOException so declaring only IOException using throws will serve the purpose here.

 

 



Please Share this page
Views : 107
Like every other website we use cookies. By using our site you acknowledge that you have read and understand our Cookie Policy, Privacy Policy, and our Terms of Service. Learn more Got it!