Java Examples - User defined Exception

Advertisements


Problem Description:

How to create user defined Exception?

Solution:

This example shows how to create user defined exception by extending Exception Class.

class WrongInputException extends Exception {
   WrongInputException(String s) {
      super(s);
   }
}
class Input {
   void method() throws WrongInputException {
      throw new WrongInputException("Wrong input");
   }
}
class TestInput {
   public static void main(String[] args){
      try {
         new Input().method();
      }
	  catch(WrongInputException wie) {
         System.out.println(wie.getMessage());
      }
   } 
}

Result:

The above code sample will produce the following result.

Wrong input


Advertisements
Advertisements