7.5. Defining Your Own Exceptions

There are two basic reasons for defining your own exception classes:

  • You want to add information when a standard exception occurs, and you can do this by rethrowing an object of your own exception class.

  • You may have error conditions that arise in your code that warrant the distinction of a special exception class.

However, you should bear in mind that there's a lot of overhead in throwing exceptions, so it is not a valid substitute for "normal" recovery code that you would expect to be executed frequently. If you have recovery code that will be executed often, then it doesn't belong in a catch block, but rather in something like an if-else statement.

Let's see how you create your own exceptions.

7.5.1. Defining an Exception Class

Your exception classes must always have Throwable as a superclass; otherwise, they will not define an exception. Although you can derive them from any of the standard exception classes, your best policy is to derive them from the Exception class. This will allow the compiler to keep track of where such exceptions are thrown in your program and check that they are either caught or declared as thrown in a method. If you use RuntimeException or one of its subclasses, the compiler checking for catch blocks of your exception class will be suppressed.

Let's go through an example of how you define an exception class:

public class DreadfulProblemException extends Exception { // Constructors public DreadfulProblemException(){ ...

Get Ivor Horton's Beginning Java™ 2, JDK™ 5th Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.