As Bill K says. Checked exceptions are easy. If your IDE/program editor doesn't give you an quick way to see method javadocs or signatures you need to throw it away. Seriously.
Unchecked exceptions are a different kettle of fish. But I think the best strategy with unchecked exceptions is to not try to catch them. Instead, you write you code so that it avoids throwing them in the first place. For example;
// ... not sure if 'obj' is null
if (obj != null) {
obj.someMethod();
}
// ... not sure if 'obj' has the right type
if (obj instanceof Foo) {
Foo foo = (Foo) obj;
}
// ... not sure if 'i' is in range
if (i >= 0 && i < array.length) {
.... = array[i];
}
Here's why I recommend this:
- A guard test is orders of magnitude more efficient than throwing and catching an exception.
- A guard test is more readable ... less lines of code.
- If you catch an unchecked exception, you can never be sure that it happened for the reasons you think it did; for example:
// obj might be null ...
try {
obj.doSomething();
} catch (NullPointerException ex) {
System.err.println("obj was null"); // WRONG!!!
// the NPE could have happen inside doSomething()
}
- If an unchecked exception is caused by a bug, you DO want a stacktrace and (depending on the application) you MAY NOT want to recover.
Obviously, you only include these "guard" checks where your understanding of the code tells you that they are necessary! So, for example if you know that 'obj' ought to be non-null and 'i' ought to be in range, it is a good idea to leave the checks out. If you leave out one test too many, you'll get an exception ... but that's good because you can then use the stacktrace to figure out why your understanding of the code was wrong, and maybe fix the underlying bug.