How to create user defined exception in Java



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.

Output String = Custom message
java_exceptions.htm
Advertisements