What are custom exceptions in Java?

Java 8Object Oriented ProgrammingProgramming

You can create your own exceptions in Java.

  • All exceptions must be a child of Throwable.
  • If you want to write a checked exception that is automatically enforced by the Handle or Declare Rule, you need to extend the Exception class.
  • If you want to write a runtime exception, you need to extend the RuntimeException class.
class MyException extends Exception {
}

You just need to extend the predefined Exception class to create your own Exception.

Example

Following is an exception which is thrown if the value passed is greater than 10.

class MyException extends Exception {
   int id;

   public MyException(int x) {
      id = x;
   }

   public String toString() {
      return "CustomException[" + id + "]";
   }
}

public class Sampleee {
   static void compute(int a) throws MyException {
      if (a > 10)
         throw new MyException(a);
         System.out.println("No error in prog. no exception caught");
   }

   public static void main(String args[]) {
   
      try {
         compute(5);
         compute(12);
      } catch(MyException ex1) {
         System.out.println(ex1);
      }
   }
}

Output

No error in prog. no exception caught
CustomException[12]
raja
Published on 08-Feb-2018 09:40:13
Advertisements