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 MyException extends Exception {
   String s1;
   MyException(String s2) {
      s1 = s2;
   } 
   @Override
   public String toString() { 
      return ("Output String = "+s1);
   }
}
public class NewClass { 
   public static void main(String args[]) { 
      try {
         throw new MyException("Custom message");
      } catch(MyException exp) {
         System.out.println(exp);
      }
   }
}

Result

The above code sample will produce the following result.

Wrong input

java_exceptions.htm

Advertisements