Tuesday, 23 October 2012

Exceptions - Java

Exception handling mechanism in java shows one major base class called Throwable. This Throwable class shows two major branches called Exception and Error.

Exception : 
Exception is abnormal condition occurred at run time. We programmers can handle these exceptions in our code using try-catch block. Example of exception is NullPointerException, FileNotFoundException etc.

Error :
Error are abnormal conditions which are not supposed to be handled by programmer. These are serious ones and we can't handle these in our program. Example of error is OutOfMemoryError, StackOerflow etc.

Again there are two types of exceptions. Checked exceptions and unchecked exception. Checked exception are those which compiler forces us to add. Like IOException. And unchecked exceptions are those which are under RunTimeException class or under Error class.

We already know how to handle exception using try-catch block. Here I am trying to explain how to handle exception between different methods. Here is simple example of that,

Code :
import java.io.IOException;

class Main
{
    public void test() throws IOException {
       
    }
   
    public void test1() throws IOException {
        test();
    }
   
    public void test2() {
        test1(); // It will create problem.
       
        try {
            test1();
        } catch(IOException e) {
           
        }
    }
    public static void main(String args[])
    {
       
    }
}

Let's examine the above code carefully. Here method test is throwing IOException so this exception will be handled by the method who is calling to test() method. Here that method is test1(); But test method is also throwing the same exception so at this point responsibility of handling that exception will be of method who is calling to test1(); So in the above code IOException throws by test() method is handled in test2() method using try-catch block.

No comments:

Post a Comment