wood burning stoves
The moose likes Beginning Java and the fly likes Good Programming Practice Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Good Programming Practice" Watch "Good Programming Practice" New topic

Good Programming Practice

bob reilly
Ranch Hand

Joined: Jan 22, 2007
Posts: 44
I've set up exception handling in a method. I've used try + catch - but no finally.

My question - very simply - is this good programming practice (no finallly). Everything I've read indicates that the three are used together - but is it necessary - or should I?

That's it. No rocket science here but any constructive comments would be appreciated. Thanks.
W. Joe Smith
Ranch Hand

Joined: Feb 10, 2009
Posts: 710
Depends on what the code in the try is. If you open some sort of connection it is good to use finally to close the connection, for example.

When I die, I want people to look at me and say "Yeah, he might have been crazy, but that was one zarkin frood that knew where his towel was."
James Elsey
Ranch Hand

Joined: Dec 21, 2007
Posts: 228

The finally block will be executed when the try/catch is complete, so unless you have to do something specific after the try/catch is finished, then there is probably no reason to use it.

Kind Regards, James. OCPJP 1.6 || My SCJP / OCJCP Study Notes
Interested in : SCJP, Google App Engine, Stripes, Android;|| My Bite-Size SCJP Study Blog
fred rosenberger
lowercase baba

Joined: Oct 02, 2003
Posts: 11955

the finally block is used for code that HAS to run, regardless of what happened in the try/catch. As the other ranchers said, if you open a connection to a database, you need to close it regardless of the success/fail of running your SQL.

If there is nothing that needs to run, there is no reason to have the finally block.

It's analogous to an if/else block. the 'if' and 'else' are often used together, but if you have no reason for an else, you don't need to code it.

There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
bob reilly
Ranch Hand

Joined: Jan 22, 2007
Posts: 44
That's great - thank you all for responding...
David Newton

Joined: Sep 29, 2008
Posts: 12617

And sometimes you use a try/finally, with no catch.
I agree. Here's the link: http://aspose.com/file-tools
subject: Good Programming Practice
It's not a secret anymore!