finally block consumes/stifles exception

Discussion in 'Java' started by Steve Claflin, Feb 13, 2006.

  1. I was rather surprised at the outcome of this code, which I created to show
    someone how a finally block will run even if the try or catch block returns
    from the method:
    Steve Claflin, Feb 13, 2006
    #1
    1. Advertising

  2. Steve Claflin

    Loveen Guest

    Hi
    Take this example...

    public class DebugFinally {
    public static void main(String[] args) {
    try{
    int number = Integer.parseInt("1245");
    }catch(Exception ex){
    System.out.println("In Catch");
    return;
    }finally{
    System.out.println("In Finally");
    }
    System.out.println("Not Returned");
    }
    }

    Output:
    In Catch
    In Finally

    As you see above the program performed what was written in Catch but
    after that it directly goes to finally block and execute what ever is
    written in it, after that it comes back to the catch block to call the
    return.

    Basically internally the compiler executes whatever is written in the
    finally block before executing any statement which takes the control
    out of try/catch construct.

    But, there is one exception to this. If I call System.exit(0); in place
    of return then, program would end abruptly without giving care to
    whatever is written in finally block.

    And in that scenario the output would be modified as follows:

    }catch(Exception ex){
    System.out.println("In Catch");
    System.exit(0);
    }finally{
    System.out.println("In Finally");
    }

    Output:
    In Catch
    Loveen, Feb 13, 2006
    #2
    1. Advertising

  3. Steve Claflin

    Rhino Guest

    "Steve Claflin" <> wrote in message
    news:eK_Hf.2468$Lr.1851@trnddc01...
    >I was rather surprised at the outcome of this code, which I created to show
    >someone how a finally block will run even if the try or catch block returns
    >from the method:
    >

    Maybe you'd like to try again? This time _with_ a code fragment?

    --
    Rhino
    Rhino, Feb 13, 2006
    #3
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Matt
    Replies:
    4
    Views:
    716
    Adam Maass
    Jul 1, 2004
  2. Replies:
    3
    Views:
    585
    k0m0r
    Jul 17, 2006
  3. Efi Merdler

    Exception in finally block

    Efi Merdler, Dec 2, 2006, in forum: Java
    Replies:
    15
    Views:
    1,145
    Thomas Hawtin
    Dec 4, 2006
  4. Artemis Fowl
    Replies:
    5
    Views:
    485
    Artemis Fowl
    Oct 28, 2005
  5. David Lozzi

    Try...Catch...Finally not firing finally?

    David Lozzi, Apr 23, 2007, in forum: ASP .Net
    Replies:
    12
    Views:
    779
    Alvin Bruney [MVP]
    May 11, 2007
Loading...

Share This Page