This week's giveaway is in the Android forum.
We're giving away four copies of Android Security Essentials Live Lessons and have Godfrey Nolan on-line!
See this thread for details.
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


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Good Programming Practice" Watch "Good Programming Practice" New topic
Author

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.


SCJA
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
Bartender

Joined: Oct 02, 2003
Posts: 11161
    
  16

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
Author
Rancher

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
 
Similar Threads
Data type for currency computations
wait in while loop?
If Statements
Java multithreading books
Need help