Java Notes

Throwing Exceptions

Prev: Exceptions

Throwing predefined exceptions

It's common to test parameters of methods or constructors for legality. But if the value is illegal, what should you do? If your class is designed to be called by other, you should define your own exceptions, so you can document the errors for them more easily.

But if your methods are only being called by your own code, you can either use an assert or throw an exception. I often use something like the following, supplying a comment with the class, method, and meaningful comment.

if (age < 0) {
    throw new IllegalArgumentException("PhysicalExam.scaleBloodPressure: age is negative");
}

Note that this shouldn't be used for illegal user input -- that should have been checked in the interface. This should only be thrown if there is a programming error. Only the programmer should see this exception.

Defining your own exceptions

You can also create your own exceptions. [Not yet written]

Define library exceptions to tell programmer they should fix their code

If you write a library that is used by others, throw your own exceptions if your code is called with illegal values, eg, something isn't initialized. Your exceptions are a way to tell the applications programmer that they should fix their code.