MY mENU


Friday, 10 February 2012

Create own exception


Steps :

1. Write our own Exception Class as extending Exception Class as SuperClass.

2. Write default constructor in our own Exception Class.

3. Write a parameterized constructor with a String as a parameter and from that call the SuperClass parameterized constructor by passing the same String.

4. Whenever needed create Object to our own Exception Class and throw it using throw statement.


example program looks like:

public class Demo{
public float add(int i,int j)throws DivisionException{
if(j==0)
throw new DivisionException("Denominator is zero");
return i/j;
}
public static void main(String[] args) {
Demo d=new Demo();
try{
System.out.println( d.add(101,-2));
}
catch(DivisionException a){

a.printStackTrace();
//System.out.print("Error messege is "+a.getMessage());
// System.out.println(a.toString());

}
}
}
Exception class is :

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

No comments:

Post a Comment