As indicated in How slow are Java exceptions? one can see that the slowness of try {} catch {}
is within the instatiation of the exception itself.
Creating an exception will fetch the entire call stack from the runtime and this is where the expense is. If you are not creating an exception, this is only very slightly an increase of time.
In the example given in this question there aren't any exceptions, one wouldn't expect any slowdown from creating them - they aren't created. Instead, what is here is a try {} finally {}
to handle resource deallocation within the finally block.
So to answer the question, no, there is no real runtime expense within a try {} finally {}
structure that doesn't use exceptions (it isn't unheard of, as seen). What is possibly expensive is the maintenance time when one reads the code and sees this not typical code style and the coder has to get their mind around that something else happens in this method after the return
before returning to the previous call.
As has been mentioned, maintenance is an argument for both ways of doing this. For the record, after consideration, my preference would be the finally approach.
Consider the maintenance time of teaching someone a new language structure. Seeing try {} finally {}
isn't something that one often sees in Java code and thus can be confusing to people. There is a degree of maintenance time for learning a bit more advanced structures in Java than what people are familiar with seeing.
The finally {}
block always runs. And this is why you should use it. Consider also the maintenance time of debugging the non-finally approach when someone forgets to include a logout at the proper time, or calls it at the improper time, or forgets to return / exit after calling it so that it is called twice. There are so many possible bugs with this that the use of try {} finally {}
makes impossible to have.
When weighing these two costs, it is expensive in maintenance time not to use the try {} finally {}
approach. While people can dicker about how many fractional milliseconds or additional jvm instructions the try {} finally {}
block is compared to the other version, one must also consider the hours spent in debugging the less than ideal way of addressing resource deallocation.
Write maintainable code first, and preferably in a way that will prevent bugs from being written later.
if(!cond)
, then it's java which made me do this. In C++, that's how I write code both of booleans and also for other types - i.e.int x;
if(!x)
. Since java allows me to use this only forbooleans
, I have totally stopped using theif(cond)
&if(!cond)
in java.(someIntValue != 0)
than comparing rather than evaluating booleans. That smells to me, and I refactor it immediately when I see it in the wild.