Saturday, October 17, 2015

Exception


What is Exception?

Exception is an episode that breaks the flow of program. Exceptions can handle in java by using handling method.

Now, let’s discuss about exception in brief.



Exceptions are of two types, CompileTimeException and RunTimeException.

CompileTimeException: This type of exception also known as Checked Exception. It means the exceptions which are caught at time of coding by compiler. If there is exception then, it must be handled or specify the exception using throws keyword.

Example, you write a java program that read a file from location “C:\java\file.txt” and prints text written in it. The program doesn’t compile, because the function main() uses FileReader() which throws a checked exception FileNotFoundException. It also uses readLine() and close() methods, and these methods also throw IOException.

import java.io.*;

public class FileReadOperation {

       public static void main(String[] args) {
              FileReader file = new FileReader("C:\\java\\file.txt");
              BufferedReader fileInput = new BufferedReader(file);

            for (int counter = 0; counter < 5; counter++)
                     System.out.println(fileInput.readLine());

              fileInput.close();
       }

}

  



RunTimeException: This type of exception also known as Un-Checked and Error. It means the exceptions which are not caught at time of coding by compiler.

Example, below program compiles without any Checked Exception, but it throws ArithmeticException when run. The compiler allows it to compile, because ArithmeticException is an unchecked exception.

public class Divide {

          public static void main(String args[]) {
                    int a = 0;
                    int b = 10;
                    int c = y/x;
                }

}


Error: Errors are those events which could not handle at developer’s level and may not even at the same time of error generation. Like any type of hardware and software problem. Example heap’s OutOfMemoryError.



http://www/try2catch.in

No comments:

Post a Comment

Thank you for your comments.