File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Good Programming Practice

 
bob reilly
Ranch Hand
Posts: 44
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 710
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
James Elsey
Ranch Hand
Posts: 228
Android IntelliJ IDE Linux
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
fred rosenberger
lowercase baba
Bartender
Pie
Posts: 12020
25
Chrome Java Linux
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
bob reilly
Ranch Hand
Posts: 44
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That's great - thank you all for responding...
 
David Newton
Author
Rancher
Posts: 12617
IntelliJ IDE Ruby
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
And sometimes you use a try/finally, with no catch.
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic