Java: Exceptions - More

Exceptions | Exception Usage | Exceptions - More

Kinds of Exceptions

There are many exceptions, but they can be put into two groups: checked exceptions and unchecked exceptions. There is some controversy about which type you should use. A discussion of some of the issues can be found at Java theory and practice: The exceptions debate.

Exception hierarchy

[Not yet written]

Multiple catch clauses

[Not yet written]

Order of catch clauses

[Not yet written]

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. This is only for your own use.

Danger from the intermediate layers - finally

Exceptions provide a good infrastructure for error processing. The simplicity of throwing an exception at a deep level and catching it at a high level may generate problems at the intermediate, skipped, levels. Did any of these methods leave any part of a data structure or resource in an inconsistent state? Each place that this may be true of needs to enclose critical code in a try...finally block.

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.

Defining your own exceptions

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