MY mENU


Sunday 17 February 2013

Custom Exception Development:


Custom Exception Development:
The new exception classes those are defined by developers are called user Defined Exception or custom exception.

These classes must be subclass of  either Throwable or any one of its subclass. It must be thrown based on condition failure.

According to the business requirements developers must write their own exception.
Its two steps process:
  1. Define public class deriving from java.lang.Exception.
  2. Define public no-arg and String parameter constructors with super() call.

For Example:
First Step:
NegativeNumberException.java

public class NegativeNumberException extends Exception
{
                public NegativeNumberException(){
                                super();
                }
                public NegativeNumberException(String msg){
                                super(msg);
                }

}

Using the above custome Exception in Our logic

Compute.java

public class Compute
{
                public int add(int n)throws NegativeNumberException
                {
                                if(n>0){
                                                return (n+10);
                                }
                                else
                                {
                                            throw new NegativeNumberException("Do Not Pass Number <=0");
                                }
                }
}

Example.java

class Example
{
                public static void main(String[] args)
                {
                                try{
                                                int n=Integer.parseInt(args[0]);
                                                Compute c=new Compute();
                                                int res=c.add(n);
                                                System.out.println("Result::"+res);
                                }
                                catch(ArrayIndexOutOfBoundsException aiobe){
                                System.out.println("Pleas pass ONE positive Integer number");
                                }
                                catch(NumberFormatException nfe){
                                System.out.println("Pleas pass only integer number");
                                }
                                catch(NegativeNumberException nne){
                                System.out.println(nne.getMessage());
                                }
                }
}