The Artima Developer Community
Sponsored Link

Legacy Java Answers Forum
June 2000



This page contains an archived post to the Java Answers Forum made prior to February 25, 2002. If you wish to participate in discussions, please visit the new Artima Forums.


try-finally answer

Posted by Ashok Fernandes on June 15, 2000 at 1:16 AM

> This is a general question regarding control flow when executing
> try-catch-finally blocks.You may refer to the following article
> on this site:
> "Under the Hood: Try-finally clauses defined and demonstrated"

> If I understand it correctly, the mini-subroutine (fianlly block)
> is called before the "termination" statement(eg return, exception etc)
> in the try block is executed.This is true for catch blocks also.Once the code in mini-subrotine is executed without
> any further control breaks, then the "termination" statement in the
> try block is executed.Now let us consider the more general case:

> try{
> if(var/0==y){
> }
> else{
> }

> }

> catch(Exception e){

> //Point B
> }

> finally {

> }
> My question is:
> In this case, since the "termination" statement in the try block
> throws an exception,where does the control go -- catch() or
> finally. That is, if the exeption is thrown, then is it that the
> subroutine is not executed and after the exception is handled in
> catch(assuming no further control breaks in catch), the
> subroutine code is executed and the control transfered back to
> try block.Now where in try block---within the if block or
> outside it?

> Please clarify.

Hi Manoj,

By executing the following code U will be able to see that once the exception (ArithmeticException) is thrown in a try block the control moves to the catch subroutine followed by the finally subroutine

public class test
public static void main(String [] args)
// testing the flow of control to finally
int x = 5;
int y = 100;
int z ;
while (true)
System.out.println(" About to perform divide ");
z = y/x;
System.out.println(" Z : " + z);
System.out.println(" X : " + x);
if ( x <0) break;
} catch (Exception e)
System.out.println(" executing finally ");

Hope this clears u'r doubt on try - catch - finally



Sponsored Links

Copyright © 1996-2009 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use - Advertise with Us