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.


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 {
      } catch(MyException ex1) {


No error in prog. no exception caught
Updated on 25-Feb-2020 10:40:37