Pages

Monday, November 15, 2010

Exceptions in Java

An Exception is an event that breaks up the normal flow of the program's instructions during the program execution.

Throwable is the parent class for Exception and Error classes.
There are two sub-types in Exception class.One is,Runtime/Unchecked Exceptions and second is,Checked Exceptions.
A simple example
that demonstrates try,catch,finally,throw,throws,user defined/custom exception type. 

package test;

public class ExceptionDemo extends Exception {  

    private String greet;   

    ExceptionDemo(String greet)

    {
        this.greet = greet;
    }   

    public String toString()
    {
        return "UserDefinedException [" + greet + "]";
    }
}
package test;

public class UserDefinedException {
    public void greetings(String greet) throws ExceptionDemo
    {
        if(greet.equalsIgnoreCase("Hello"))
            System.out.println("Hello everybody...!!!");
        else
            throw new ExceptionDemo(greet);
    }  

    public static void main(String[] args) {
        try {
            new UserDefinedException().greetings("Hello");
            new UserDefinedException().greetings("Go to Hell");
        }
        catch(ExceptionDemo ed)
        {
            System.out.println("Exception Caught : " ed);
        }
        finally
        {
            System.out.println("In finally block...!!!");
        }
    }
}

1 comment:

  1. It would be great if you can explain the flow of the code. So, java dummies like me can understand better.

    Great work..Keep going

    ReplyDelete