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.
NullPointerException
or ArrayIndexOutOfBoundsException.
If you do, there is something wrong with your program, and you
need to fix it. You usually don't catch unchecked exceptions.
Instead, fix your program so it can't produce one of these.
However, NumberFormatException is the one exception of this type
that is usually caught.
try statement.
[Not yet written]
[Not yet written]
[Not yet written]
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.
finallyExceptions 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.
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.
You can also create your own exceptions. [Not yet written]