Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
JavaRanch.com/granny.jsp
The moose likes Beginning Java and the fly likes try catch finally Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Soft Skills this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "try catch finally" Watch "try catch finally" New topic
Author

try catch finally

bob reilly
Ranch Hand

Joined: Jan 22, 2007
Posts: 44
I was asked to modified software invoked via a try catch finally block. After modifying the software I thought I may need to exit out of the try block and go to the finally section.

Two questions:
- is exiting a try block good coding practice/
- how would you go about doing it. System.exit will not execute the finally block.

Any URL / examples / alternatives would be appreciated. Thanking you in advance...
Siva Masilamani
Ranch Hand

Joined: Sep 19, 2008
Posts: 385
how about return?


SCJP 6,SCWCD 5,SCBCD 5

Failure is not an option.
bob reilly
Ranch Hand

Joined: Jan 22, 2007
Posts: 44
Could you provide an example? I provided syntax:

if (ot_lunch.equals(""))
{ return; } // this fails...

Am I having a brain hiccup here? It looks simple and yet...


David Newton
Author
Rancher

Joined: Sep 29, 2008
Posts: 12617

Please see ItDoesntWorkIsUseless.

Is your method supposed to return a value? A return doesn't just "fail"--there's either a compilation error, a logic error, *something*.
David Newton
Author
Rancher

Joined: Sep 29, 2008
Posts: 12617

Whether or not to "exit" a try block depends on the situation, code style/standards, etc.
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 14430
    
  23

What exactly do you mean by "exit out of the try block and go to the finally section"? Can you give a code example that explains what you mean?

The code in the finally-block is normally always executed (unless, for example, you stop the JVM by calling System.exit()). Have a look at this:



Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 8 API documentation
bob reilly
Ranch Hand

Joined: Jan 22, 2007
Posts: 44
Got it. The return syntax worked. And yes - a return of an object was required (David - you were right). Once that was built - I was able to go to 'finally'.

Thank you all for your responding.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: try catch finally