Tim Holloway wrote:. . . However, it's always best to actually measure the specific conditions rather than optimize based on what you "know". . . .
The copy of
Core JavaII by Cay Horstmann, which I had the good fortune to win in the JiG forum back in the Spring says they tested
ifs
vs Exceptions and found the exceptions were about 50× slower. But never mind the width, feel the quality. Sorry. Never mind the speed, feel the elegance. A throw and a catch in the same method look inelegant, and they are not really what an exception is for. At least that is what I think.
The idea of an exception is for method A to tell method B that it didn't work. Then method B can consider whether to take action (catch) or let another method take action (let the exception propagate). The bit of code shown seems specially designed to be confusing and to produce NPEs.
No need for a try there.
But what is wrong with NPEs? If you get a
null which you don't want, throw NPEs. The bigger they are and the harder you throw them, the better. And throw them as soon as the
null makes its presence felt. Don't wait until it can do harm elsewhere. Splat the blighter! The wrong thing to do with NPEs is to catch them. They should be allowed to propagate until your users learn to avoid
nulls. And setting a local variable to an initial value of
null; well at least it is only in a forum post and not in real‑life code.
MT: if you are going to catch exceptions, avoid
catch (Exception exc), even if you see it in books. Use the most specific type of Exception you can force into your code. Use multiple
catch blocks if the different sorts of Exception require different actions. Read more about Exceptions in the
Java™ Tutorials.