How to write your own Exception and use it

1. Crete your Exception class that extends java.lang.Exception class. You may overide constructors and methods as you wish.

public classMyExceptionextendsException {

    public MyException() {
        super();
    }
    public MyException(String message) {
        super(message);
    }
    public MyException(String message, Throwable cause) {
        super(message, cause);
    }
    public MyException(Throwable cause) {
        super(cause);
    }
}

2. Simply throw that Exception from any other Java class.

public class MyExceptionTest {   
    public static void main(String[] args) {       
        MyExceptionTest myExceptionTest = new MyExceptionTest();
        try{
            myExceptionTest.test();  
        }catch(MyException e){
            e.printStackTrace();
            System.out.println(e.getMessage());
        }
    }   
    public void test() throws MyException {    
        // simply throw an exception here   
        throw newMyException ("MyOwnException");       
    }
}