Creating and Using Your Own Exception Classes

Contact Us or call 1-877-932-8228
Creating and Using Your Own Exception Classes

Creating and Using Your Own Exception Classes

You can create your own exception class by extending an existing exception class.

[modifiers] class NewExceptionClassName extends ExceptionClassName {
	create constructors that usually delegate to super-constructors
}

You could then add any fields or methods that you wish, although often that is not necessary.

You must, however, override any constructors you wish to use: Exception(), Exception(String message), Exception(String message, Throwable cause), Exception(Throwable cause). Usually you can just call the corresponding super-constructor.

If you extend RuntimeException or one of its subclasses, your exception will be treated as a runtime exception (it will not be checked).

When a situation arises for which you would want to throw the exception, use the throw keyword with a new object from your exception class, for example:

throw new ExceptionClassName(messageString);

Code Sample:

Java-Exceptions/Demos/NewExceptionTest.java
class NewException extends Exception {
  NewException() {
    super();
  }
  NewException(String message) {
    super(message);
  }
  NewException(String message, Throwable cause) {
    super(message, cause);
  }
  NewException(Throwable cause) {
    super(cause);
  }
}
public class NewExceptionTest {
  public void thrower() throws NewException {
    if (Math.random() < 0.5) {
      throw new NewException("This is my exception");
    }
  }
  public static void main(String[] args) {
    NewExceptionTest t = new NewExceptionTest();
    try {
      t.thrower();
    }
    catch(NewException e) {
      System.out.println("New Exception: " + e.getMessage());
    }
    finally {
      System.out.println("Done");
    }
  }
}

The thrower method randomly throws a NewException, by creating and throwing a new instance of NewException.

main tries to call thrower, and catches the NewException when it occurs.

Next