Do you need finally when your method throws Exception..

Discussion in 'Java' started by Tomas, Sep 28, 2005.

  1. Tomas

    Tomas Guest

    Hi,

    If you have a method that throws some Exception lik this:

    public void doSomething(){throws SomeException

    Do you then need a finally block in that method, if you i.e want to close
    streams and such. I mean when this Exception occurs do it jump out of the
    method direct or does it finish the rest of the method.

    I wonder cause i tried to have a finally block in a method that did not have
    any try and catch blocks så the compiler complained.

    Best Regards
    /Tomas
    Tomas, Sep 28, 2005
    #1
    1. Advertising

  2. On Wed, 28 Sep 2005 22:01:26 +0000, Tomas wrote:

    > Do you then need a finally block in that method, if you i.e want to close
    > streams and such. I mean when this Exception occurs do it jump out of the
    > method direct or does it finish the rest of the method.


    It abruptly terminates the method. This means that nothing after the
    exception is executed, and the method immediately returns with an
    Exception - unless you put some code into a finally block

    --
    You can't run away forever,
    But there's nothing wrong with getting a good head start.
    --- Jim Steinman, "Rock and Roll Dreams Come Through"
    Stefan Schulz, Sep 28, 2005
    #2
    1. Advertising

  3. Tomas

    Jon Haugsand Guest

    *
    > Hi,
    >
    > If you have a method that throws some Exception lik this:
    >
    > public void doSomething(){throws SomeException
    >
    > Do you then need a finally block in that method, if you i.e want to close
    > streams and such. I mean when this Exception occurs do it jump out of the
    > method direct or does it finish the rest of the method.
    >
    > I wonder cause i tried to have a finally block in a method that did not have
    > any try and catch blocks så the compiler complained.


    You should catch the exception in question if you can use a finally
    block. But don't try to catch too many exceptions and only those you
    can cope with. Bad exceptions, i.e. things that has to do with
    programming errors, should never be catched anywhere (but at some
    point where logging and bug reporting can take place).

    --
    Jon Haugsand
    Dept. of Informatics, Univ. of Oslo, Norway, mailto:
    http://www.ifi.uio.no/~jonhaug/, Phone: +47 22 85 24 92
    Jon Haugsand, Sep 28, 2005
    #3
  4. Tomas wrote:
    >
    > Do you then need a finally block in that method, if you i.e want to close
    > streams and such. I mean when this Exception occurs do it jump out of the
    > method direct or does it finish the rest of the method.


    Whenever you acquire a resource, you must make sure always release it.
    If your method allocates a resource and then throws an exception
    removing any reference to the resource, you should ensure that the
    resource is released.

    > I wonder cause i tried to have a finally block in a method that did not have
    > any try and catch blocks så the compiler complained.


    You need the try block. The syntax should be:

    try {
    ...
    } finally {
    ...
    }

    Tom Hawtin
    --
    Unemployed English Java programmer
    http://jroller.com/page/tackline/
    Thomas Hawtin, Sep 28, 2005
    #4
  5. Tomas

    Roedy Green Guest

    On 28 Sep 2005 22:01:26 GMT, "Tomas" <> wrote or
    quoted :

    >Do you then need a finally block in that method, if you i.e want to close
    >streams and such. I mean when this Exception occurs do it jump out of the
    >method direct or does it finish the rest of the method.


    an exception leaves the method immediately (if there is no try
    block).. The idea is something has gone wrong so calculation cannot
    proceed. E.g. NullPointerExeception. There is nothing we CAN do
    without even an object to run the next method on.

    It will keep propagating up blocks and calls till it finds a try block
    willing to catch the exception. In each case it exits the block or
    method immediately.

    Of course you can use finally to do your cleanup, most commonly file
    closing.


    --
    Canadian Mind Products, Roedy Green.
    http://mindprod.com Again taking new Java programming contracts.
    Roedy Green, Sep 29, 2005
    #5
  6. Tomas

    zero Guest

    "Tomas" <> wrote in
    news:433b12b6$0$16194$:

    >
    > Hi,
    >
    > If you have a method that throws some Exception lik this:
    >
    > public void doSomething(){throws SomeException
    >
    > Do you then need a finally block in that method, if you i.e want to
    > close streams and such. I mean when this Exception occurs do it jump
    > out of the method direct or does it finish the rest of the method.
    >
    > I wonder cause i tried to have a finally block in a method that did
    > not have any try and catch blocks så the compiler complained.
    >
    > Best Regards
    > /Tomas
    >
    >


    The best way to understand the program flow when using exceptions is just
    to try it out. Set output statements everywhere you can, and then
    examine what you get. Something like this:

    public static void method1() throws Exception
    {
    System.out.println("method1 starts");
    throw new Exception("exception in method1");
    System.out.println("method1 ends");
    }

    public static void main(String args[])
    {
    System.out.println("main starts");
    try
    {
    method1();
    }
    catch(Exception e)
    {
    System.out.println("exception caught");
    e.printStackTrace();
    }
    finally
    {
    System.out.println("finally block executes");
    }
    System.out.println("main ends");
    }

    Here you will see that the "method1 ends" output will never be reached,
    because the program flow is interrupted by the Exception. If you comment
    out (or remove) the throw line, method1 will end normally, and the
    "exception caught" line will be skipped. In either case the finally
    block will be executed though.
    You can never have a catch or finally block without a try block.

    If you open resources locally in method1, it is best to do something like
    this:

    public void method1() throws Exception
    {
    SomeResource resource = null;
    try
    {
    // open and use the resource
    }
    finally
    {
    if(resource == null)
    resource.close();
    }
    }

    Here the resource will be closed, wether or not an exception occurs,
    because the finally block always executes. Since you're not catching any
    exceptions, they will be thrown to be handled by the calling method.

    Of course ideally you should not use Exception, but a subclass of it.
    zero, Sep 29, 2005
    #6
  7. zero wrote:
    >
    > SomeResource resource = null;
    > try
    > {
    > // open and use the resource
    > }
    > finally
    > {
    > if(resource == null)
    > resource.close();
    > }
    > }


    It's much better to write:

    final SomeResource resource = ...acquire resource ... ;
    try {
    ... use the resource ..
    } finally {
    resource.close();
    }

    Tom Hawtin
    --
    Unemployed English Java programmer
    http://jroller.com/page/tackline/
    Thomas Hawtin, Sep 29, 2005
    #7
  8. Tomas

    zero Guest

    Thomas Hawtin <> wrote in news:433c3fd0$0$73618
    $:

    > zero wrote:
    > >
    >> SomeResource resource = null;
    >> try
    >> {
    >> // open and use the resource
    >> }
    >> finally
    >> {
    >> if(resource == null)
    >> resource.close();
    >> }
    >> }

    >
    > It's much better to write:
    >
    > final SomeResource resource = ...acquire resource ... ;
    > try {
    > ... use the resource ..
    > } finally {
    > resource.close();
    > }
    >
    > Tom Hawtin



    It's quite possible that the method to acquire the resource returns null.
    To account for this possibility without ignoring other possibilities, I
    always assign it to be null first, and in the finally block check for that.
    NullPointerExceptions are no fun.
    zero, Sep 29, 2005
    #8
  9. Tomas

    Roedy Green Guest

    On Thu, 29 Sep 2005 18:29:55 GMT, zero <> wrote or quoted
    :

    > if(resource == null)
    > resource.close();

    you meant to say

    if ( resource != null )
    {
    resource.close();
    }
    --
    Canadian Mind Products, Roedy Green.
    http://mindprod.com Again taking new Java programming contracts.
    Roedy Green, Sep 29, 2005
    #9
  10. Tomas

    zero Guest

    Roedy Green <> wrote in
    news::

    > On Thu, 29 Sep 2005 18:29:55 GMT, zero <> wrote or quoted
    >:
    >
    >> if(resource == null)
    >> resource.close();

    > you meant to say
    >
    > if ( resource != null )
    > {
    > resource.close();
    > }


    oops, of course. Thanks for the correction :)
    zero, Sep 29, 2005
    #10
  11. zero wrote:
    > Thomas Hawtin <usenet@tacklin
    >
    > It's quite possible that the method to acquire the resource returns null.


    If that is the case, it's probably best to check against null before you
    use it! NullPointerExceptions are no fun.

    > To account for this possibility without ignoring other possibilities, I
    > always assign it to be null first, and in the finally block check for that.
    > NullPointerExceptions are no fun.


    I don't like the way Java handles null (not that I can give an example
    of a language that does it as I would like). When I started with Java I
    took the attitude that nulls were inevitable and I should embrace them.
    My view now is that they should be stamped them out at the earliest
    possible point, and be very carefully to articulate exactly which
    reference may be null and what the interpretation of the null should be.

    Tom Hawtin
    --
    Unemployed English Java programmer
    http://jroller.com/page/tackline/
    Thomas Hawtin, Sep 29, 2005
    #11
  12. Tomas

    Roedy Green Guest

    On Thu, 29 Sep 2005 22:06:29 +0100, Thomas Hawtin
    <> wrote or quoted :

    >I don't like the way Java handles null (not that I can give an example
    >of a language that does it as I would like). When I started with Java I
    >took the attitude that nulls were inevitable and I should embrace them.
    >My view now is that they should be stamped them out at the earliest
    >possible point, and be very carefully to articulate exactly which
    >reference may be null and what the interpretation of the null should be.


    Early on I wanted them to behave like somenullobject.method()
    But then you would have to define these default null objects.
    --
    Canadian Mind Products, Roedy Green.
    http://mindprod.com Again taking new Java programming contracts.
    Roedy Green, Sep 30, 2005
    #12
  13. Tomas

    zero Guest

    Thomas Hawtin <> wrote in
    news:433c576c$0$15060$:

    > zero wrote:
    >> Thomas Hawtin <usenet@tacklin
    >>
    >> It's quite possible that the method to acquire the resource returns
    >> null.

    >
    > If that is the case, it's probably best to check against null before
    > you use it! NullPointerExceptions are no fun.


    that's why the code that uses it is in a try block :)
    zero, Sep 30, 2005
    #13
  14. Tomas

    steve Guest

    On Fri, 30 Sep 2005 04:50:13 +0800, zero wrote
    (in article <Xns96E0E84BBAEEzerothishi@195.130.132.72>):

    > Roedy Green <> wrote in
    > news::
    >
    >> On Thu, 29 Sep 2005 18:29:55 GMT, zero <> wrote or quoted
    >>>

    >>
    >>> if(resource == null)
    >>> resource.close();

    >> you meant to say
    >>
    >> if ( resource != null )
    >> {
    >> resource.close();
    >> }

    >
    > oops, of course. Thanks for the correction :)


    actually it is going to be more like:

    if ( resource != null ){
    try{
    resource.close();
    }
    catch(Exception e)
    {
    System.out.println("serious error , failed to close resource XYZ");
    e.printStackTrace();
    }
    finally
    {
    // this is supposed to be empty
    }
    steve, Oct 1, 2005
    #14
  15. Tomas

    Roedy Green Guest

    On Sun, 2 Oct 2005 06:17:40 +0800, steve <> wrote or
    quoted :

    >if ( resource != null ){
    >try{
    >resource.close();
    >}


    most close methods don't throw an exception. The almost random way
    some methods of the same name throw exceptions and others do not is
    one of the most infuriating thing about writing Java i/o code. I
    eventually ripped all the interrupt handling code out of the file I/O
    amanuensis because it was so convoluted and there was so little
    regularity.
    --
    Canadian Mind Products, Roedy Green.
    http://mindprod.com Again taking new Java programming contracts.
    Roedy Green, Oct 2, 2005
    #15
  16. Tomas

    steve Guest

    On Sun, 2 Oct 2005 10:16:54 +0800, Roedy Green wrote
    (in article <>):

    > On Sun, 2 Oct 2005 06:17:40 +0800, steve <> wrote or
    > quoted :
    >
    >> if ( resource != null ){
    >> try{
    >> resource.close();
    >> }

    >
    > most close methods don't throw an exception. The almost random way
    > some methods of the same name throw exceptions and others do not is
    > one of the most infuriating thing about writing Java i/o code. I
    > eventually ripped all the interrupt handling code out of the file I/O
    > amanuensis because it was so convoluted and there was so little
    > regularity.
    >


    they do in the oracle sql drivers, so i always trap my close statements , i
    also write defensive code.

    i always :
    1.include a finally in my exception routines, even when empty.
    2. write if (){} else{ // this is supposed to be empty} , even when the else
    is empty

    ultimately the compiler rips it out , but i do it for documentation .

    steve
    steve, Oct 4, 2005
    #16
  17. Tomas

    Stefan Ram Guest

    steve <> writes:
    >i always :
    >1.include a finally in my exception routines, even when empty.
    >2. write if (){} else{ // this is supposed to be empty} , even when the else
    >is empty


    I also like to include the brace "}" on the same line, but then
    it prefer "/* ... */"-comments, because the "//"-comment would
    also hide the final brace "}" on that line.
    Stefan Ram, Oct 4, 2005
    #17
  18. Tomas

    steve Guest

    On Wed, 5 Oct 2005 06:39:04 +0800, Stefan Ram wrote
    (in article <-berlin.de>):

    > steve <> writes:
    >> i always :
    >> 1.include a finally in my exception routines, even when empty.
    >> 2. write if (){} else{ // this is supposed to be empty} , even when the
    >> else
    >> is empty

    >
    > I also like to include the brace "}" on the same line, but then
    > it prefer "/* ... */"-comments, because the "//"-comment would
    > also hide the final brace "}" on that line.
    >

    linefeed problem, the braces would obviously go on a sep. line, besides it
    would not compile!!

    however I hate /**/ comments.

    if you have a large body of code with
    /**/ scattered thru out & you want to comment out a large section of code
    that happends to contain /**/, then it can get very messy!!


    steve
    steve, Oct 5, 2005
    #18
    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. Chris Miller
    Replies:
    4
    Views:
    13,272
    Chris Smith
    Nov 22, 2003
  2. Duncan Strang
    Replies:
    6
    Views:
    2,090
    John C. Bollinger
    Mar 3, 2004
  3. David Lozzi

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

    David Lozzi, Apr 23, 2007, in forum: ASP .Net
    Replies:
    12
    Views:
    780
    Alvin Bruney [MVP]
    May 11, 2007
  4. Replies:
    2
    Views:
    324
  5. jrobinss
    Replies:
    32
    Views:
    960
Loading...

Share This Page