wood burning stoves 2.0*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Finally block executing before catch PRoblem Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Finally block executing before catch PRoblem" Watch "Finally block executing before catch PRoblem" New topic
Author

Finally block executing before catch PRoblem

Mohit G Gupta
Ranch Hand

Joined: May 18, 2010
Posts: 634



i think answer should be:

Inside fnA
Exception Caught
fnA's finally
Inside fnB
fnB's finally

but the correct answer is:


Inside fnA
fnA's finally
Exception Caught
Inside fnB
fnB's finally

OCPJP 6.0 93%
OCPJWCD 5.0 98%
Rahul Sudip Bose
Ranch Hand

Joined: Jan 21, 2011
Posts: 637

mohitkumar gupta wrote:

i think answer should be:

Inside fnA
Exception Caught
fnA's finally
Inside fnB
fnB's finally



Why do you think so ? The method fnA will complete and then execution of code in main method occurs.


SCJP 6. Learning more now.
Matthew Brown
Bartender

Joined: Apr 06, 2010
Posts: 4372
    
    8

The finally block in fnA executes before that method is exited. The exception can't be caught until after the method is exited, so the given answer is correct.
Piyush Joshi
Ranch Hand

Joined: Jun 10, 2011
Posts: 207

Finally block inside a method should execute before the method returns or throws an exception.

A most common use of finally block is to close the jdbc connection object.

for example:

finally{
conn.close();
}

where conn is the reference to the connection object.

But now imagin what will happen if method returned before finally got executed. --> There will be no conn reference available to finally block because the local stack variables for the method would be gone.

So it is quite logical to think that finally block should be executed before method returns or throws exception.


Piyush
Mohit G Gupta
Ranch Hand

Joined: May 18, 2010
Posts: 634

i didn't get it.
why is the finally block executing after catch?
Matthew Brown
Bartender

Joined: Apr 06, 2010
Posts: 4372
    
    8

mohitkumar gupta wrote:i didn't get it.
why is the finally block executing after catch?

Because the catch is in a completely different method. Once you're outside fnA, you're outside it. The finally block will be the last thing that happens inside fnA, but the catch doesn't happen till you've left it.
joy b chakravarty
Ranch Hand

Joined: May 16, 2011
Posts: 62

On similar lines...


what do you think gets printed here.
Answer> Value : 2.

Cheers, Joy [SCJP 1.4, SCBCD 5.0]
get high on alcohol, algorithm or both
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Finally block executing before catch PRoblem