How to define custom Exception ?


To define custom exception crate a sub class of exception and either override toString() method or provide default as well as augmented constructor. Argumented constructor must receive message as String.
public class MyException extends Exception{
    String msg="Exception";
    public MyException() {
        super();
    }
    public MyException(String msg){
        super(msg);
    }
//or
    @Override
    public String toString(){
        return msg;
    }
}

public class Test{

    public static void main(String as[]) {
        try {
            int x = 10;
            int y = 0;
if(y==0)
throw new MyException("Exception");
            int z = x / y;
            System.out.pritln(z);
              
        } catch (Throwable e) {
            System.out.println(e);
        }

    }
}
If both toString () and constructor is used then toString () is given priority.

Comments

Popular posts from this blog

What is Struts Framework?

HOW TO ACCESS SESSION IN STRUTS 2 WITH EXAMPLE

Why java uses both compiler and interpreter?