wrote:
> Hi. I wanted to use exceptions to handle error conditions in my code.
> I think doing that is useful, as it helps to separate "go" paths from
> error paths. However, a coding guideline has been presented that says
> "Use conventional error-handling techniques rather than exception
> handling for straightforward local error processing in which a program
> is easily able to deal with its own errors."
>
> By "conventional error-handling," I believe they mean returning an
> error code, or just handling the error without going to a catch block.
>
>
> When I said that I'd prefer throwing and catching exceptions--and that,
> in fact, exceptions is the "conventional error-handling technique" in
> Java, I was told that since we have a real-time system, we can't afford
> the performance hit caused by using exceptions.
>
> Do exception blocks cause big performance hits? If so, what causes the
> hit? Or is the person just misinformed?
Creating, throwing, catching, and eventually garbage-
collecting a Throwable object is certainly a lot more work
than a simple `if'. You can measure it for yourself by
comparing the time required for two different ways of
filling an array:
for (int i = 0; i < array.length; ++i)
array[i] = i;
try {
for (int i = 0; ; ++i)
array[i] = i;
} catch (ArrayIndexOutOfBoundsException ex) {}
(This is pretty much the same experiment Joshua Bloch shows
in "Effective Java.") On the machine I'm using at the moment,
the exception-based approach takes 15.5 times as long as the
straightforward loop to fill a 100-element array; that is, one
exception takes longer than 1500 limit tests. Your machine
may give different timings; try it and see.
Note that the guidance you've been given does not forbid
the use of exceptions; it only forbids them for "straightforward
local error processing." I suggest you go back to the folks
who wrote the guidelines and ask what "straightforward" means;
it will probably turn out to be less burdensome than you seem
to fear.
--