The Artima Developer Community
Sponsored Link

Exceptions are free unless thrown



This page contains an archived post to the Design Forum (formerly called the Flexible Java Forum) made prior to February 25, 2002. If you wish to participate in discussions, please visit the new Artima Forums.


Exceptions are free unless thrown

Posted by Bill Venners on 10 Jul 1998, 8:55 AM

> For me, this whole thing stemmed from reconstituting Objects after serialization. Some data members were declared transient (or didn't implement Serializable). So I was faced with the decision of cluttering up constructors with "initialization" methods, recreating the data members on readObject (directly or using the same "initialization" methods), wrapping their usage in a try/catch clause (looking for NullPointerExceptions) or just checking to see if the memebers != null. I opted for the try/catch (for better or worse) since the members really have one time that they were actually == null. So I guess the question is, "If I know that 99.999% of the time I will not throw an Exception, what is the cost of a try/catch clause?"

I think I understand your situation. The answer to your question,
I believe, is that if you don't actually throw an exception,
then having a try/catch clause is "free" from the perpective
of execution time. The JVM has to check every usage of the
reference for null, because whether or not you have a catch
clause for NullPointerException, the VM is going to throw it
if you try to use a null reference. (Or, if the VM is able to
optimize out the check for null, it will not check for null
regardless of whether you have a catch clause or not.)

So the VM has to do the same thing as it executes along whether
or not you have the try/catch there. It is only if the exception
is actually thrown that the performance hit comes. To get an
idea how expensive a throw/catch is, check out:

The only other cost I can think of that would come from having
try/catch blocks is that it could make your class file
bigger, which could slow download times, but this is likely
going to be minutia.



Sponsored Links

Copyright © 1996-2009 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use - Advertise with Us