Java - Exception Class Creation


You can create your own exception classes.

They must extend an existing exception class.


The keyword extends is used to extend a class.

<Class Modifiers> class ClassName extends <<Superclass Name>> {

ClassName is your exception class name and <<Superclass Name>>is an existing exception class name.

To create a MyException class, which extends the java.lang.Exception class.

The syntax would be as follows:

public class MyException extends Exception {
   // Body for MyException class goes here


public class Main {

  public static void main(String[] args) throws Exception {

    try {/*from   w  w  w  .  j  a  va 2 s . com*/
      throw new MyException("File not found");
    } catch (MyException e) {
      // Code for the catch block goes here

class MyException extends Exception {

  public MyException() {

  public MyException(String message) {

  public MyException(String message, Throwable cause) {
    super(message, cause);

  public MyException(Throwable cause) {