Java custom exception class

In this chapter you will learn:

  1. Creating Your Own Exception Subclasses
  2. Example - How to create your own exception subclasses

Description

You can create your own exception class by defining a subclass of Exception.

The Exception class does not define any methods of its own. It inherits methods provided by Throwable.

Example

The following program creates a custom exception type.


class MyException extends Exception {
  private int detail;
//from   w  ww . j  av  a2  s  .  c om
  MyException(int a) {
    detail = a;
  }

  public String toString() {
    return "MyException[" + detail + "]";
  }
}

public class Main {
  static void compute(int a) throws MyException {
    System.out.println("Called compute(" + a + ")");
    if (a > 10)
      throw new MyException(a);
    System.out.println("Normal exit");
  }

  public static void main(String args[]) {
    try {
      compute(1);
      compute(20);
    } catch (MyException e) {
      System.out.println("Caught " + e);
    }
  }
}

The code above generates the following result.

Next chapter...

What you will learn in the next chapter:

  1. How to use chained exceptions
  2. Syntax for chained exceptions
  3. Example - use chained exceptions
Home »
  Java Tutorial »
    Java Langauge »
      Java Exception Handling
Java Exception
Java Exception types
Java try catch statement
Java throw statement
Java throws statement
Java finally statement
Java Built-in Exceptions
Java custom exception class
Java chained exceptions