Try ... Catch ... Finally confusion

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Sean Kirkpatrick

    #1

    Try ... Catch ... Finally confusion

    I got caught with my pants down the other day when trying to explain
    Try...Catch...F inally and things didn't work as I had assumed. Perhaps
    someone can explain to me the purpose of Finally. I've looked at several
    texts that I have and none of them address this specific point.

    If I call some method that throws an exception in my routine Foo,

    sub foo
    call bar <- throws an exception
    do something else <- never get here
    end sub

    control is passed back up the call stack to the first valid catch block.
    So far so good.

    Now if I do this

    sub foo
    try
    call bar (which throws an exception)
    catch
    handle the exception <- only if exception thrown
    end try

    do something else <- since exception handled, do this

    end sub

    execution goes to the catch block and then continues to do something
    else. So far so good.

    If I do this

    sub foo
    try
    call bar (which throws an exception)
    catch
    handle the exception <- only if exception thrown
    finally
    always do this
    end try

    do something else <- since exception handled, do this

    end sub

    the Finally block ALWAYS gets executed regardless of an exception being
    thrown. Ok.

    I submit that the second case is identical to the third case if I
    rewrite number 2 as follows:


    sub foo
    try
    call bar (which throws an exception)
    catch
    handle the exception <- only if exception thrown
    end try

    always do this
    do something else <- since exception handled, do this

    end sub

    This begs the question - what is the use of Finally? I had assumed,
    wrongly as it turns out, that in the event of an exception, Catch and
    Finally would execute and control would return to the caller. If no
    exception, Finally would execute and control continues to the next
    statement.

    I can see no use for Finally!

    Sean
  • Mythran

    #2
    Re: Try ... Catch ... Finally confusion

    [color=blue]
    > sub foo
    > try
    > call bar (which throws an exception)
    > catch
    > handle the exception <- only if exception thrown
    > finally
    > always do this
    > end try
    >
    > do something else <- since exception handled, do this
    >
    > end sub
    >
    > the Finally block ALWAYS gets executed regardless of an exception being
    > thrown. Ok.
    >
    > I submit that the second case is identical to the third case if I
    > rewrite number 2 as follows:
    >
    >
    > sub foo
    > try
    > call bar (which throws an exception)
    > catch
    > handle the exception <- only if exception thrown
    > end try
    >
    > always do this
    > do something else <- since exception handled, do this
    >
    > end sub
    >
    > This begs the question - what is the use of Finally? I had assumed,
    > wrongly as it turns out, that in the event of an exception, Catch and
    > Finally would execute and control would return to the caller. If no
    > exception, Finally would execute and control continues to the next
    > statement.
    >
    > I can see no use for Finally!
    >
    > Sean[/color]

    The finally always runs. After the finally, it's iffy. For example:

    Dim conn As SqlConnection = New SqlConnection(. ..)
    Dim ds As DataSet
    Try
    ds = GetDataFromData base(conn)
    Catch ex As SqlException
    ' Log the error message or handle it some other way.
    Return
    Finally
    ' Perform cleanup, whether or not an exception was raised as well
    ' as whether or not we are exiting the function because of a
    ' raised exception, we still need to close the instance of the
    ' SqlConnection object...we can do that here. If we try to
    ' Return anywhere in a Try..Catch block, Finally will still be
    ' executed.
    conn.Close()
    End Try

    ' We only get this far if an exception was not thrown. The Finally
    ' block above was executed and the connection was closed.
    DoSomethingWith TheDataSet(ds)

    HTH! :)

    Mythran

    Comment

    • m.posseth

      #3
      Re: Try ... Catch ... Finally confusion

      Finally always runs even if you are in a function and perform a hard return
      statement finally is run ,, so it is the perfect place to put in code that
      should run nomather what ( for example object cleanup code )

      regrds

      Michel Posseth

      "Sean Kirkpatrick" <nannernanner@c ommunity.nospam > wrote in message
      news:%23KfWeNtv FHA.1256@TK2MSF TNGP09.phx.gbl. ..[color=blue]
      >I got caught with my pants down the other day when trying to explain
      >Try...Catch... Finally and things didn't work as I had assumed. Perhaps
      >someone can explain to me the purpose of Finally. I've looked at several
      >texts that I have and none of them address this specific point.
      >
      > If I call some method that throws an exception in my routine Foo,
      >
      > sub foo
      > call bar <- throws an exception
      > do something else <- never get here
      > end sub
      >
      > control is passed back up the call stack to the first valid catch block.
      > So far so good.
      >
      > Now if I do this
      >
      > sub foo
      > try
      > call bar (which throws an exception)
      > catch
      > handle the exception <- only if exception thrown
      > end try
      >
      > do something else <- since exception handled, do this
      >
      > end sub
      >
      > execution goes to the catch block and then continues to do something else.
      > So far so good.
      >
      > If I do this
      >
      > sub foo
      > try
      > call bar (which throws an exception)
      > catch
      > handle the exception <- only if exception thrown
      > finally
      > always do this
      > end try
      >
      > do something else <- since exception handled, do this
      >
      > end sub
      >
      > the Finally block ALWAYS gets executed regardless of an exception being
      > thrown. Ok.
      >
      > I submit that the second case is identical to the third case if I rewrite
      > number 2 as follows:
      >
      >
      > sub foo
      > try
      > call bar (which throws an exception)
      > catch
      > handle the exception <- only if exception thrown
      > end try
      >
      > always do this
      > do something else <- since exception handled, do this
      >
      > end sub
      >
      > This begs the question - what is the use of Finally? I had assumed,
      > wrongly as it turns out, that in the event of an exception, Catch and
      > Finally would execute and control would return to the caller. If no
      > exception, Finally would execute and control continues to the next
      > statement.
      >
      > I can see no use for Finally!
      >
      > Sean[/color]



      Comment

      • topdawg147@hotmail.com

        #4
        Re: Try ... Catch ... Finally confusion

        Sometimes you don't want to handle the error at this function. That is,
        you'll handle it somewhere else up the chain. If this happens, you
        still need to clean up everything. Also, you don't have to use Catch in
        a Try statement.

        Try

        Cursors.Current = Cursor.WaitCurs or
        ListView1.Begin Update()

        ' Do stuff.

        Finally
        Cursors.Current = Cursor.Default
        ListView1.EndUp date()
        End Try

        Comment

        • Paul Clement

          #5
          Re: Try ... Catch ... Finally confusion

          On Wed, 21 Sep 2005 10:39:05 -0700, Sean Kirkpatrick <nannernanner@c ommunity.nospam > wrote:


          ¤ If I do this
          ¤
          ¤ sub foo
          ¤ try
          ¤ call bar (which throws an exception)
          ¤ catch
          ¤ handle the exception <- only if exception thrown
          ¤ finally
          ¤ always do this
          ¤ end try
          ¤
          ¤ do something else <- since exception handled, do this
          ¤
          ¤ end sub
          ¤
          ¤ the Finally block ALWAYS gets executed regardless of an exception being
          ¤ thrown. Ok.
          ¤
          ¤ I submit that the second case is identical to the third case if I
          ¤ rewrite number 2 as follows:
          ¤
          ¤
          ¤ sub foo
          ¤ try
          ¤ call bar (which throws an exception)
          ¤ catch
          ¤ handle the exception <- only if exception thrown
          ¤ end try
          ¤
          ¤ always do this
          ¤ do something else <- since exception handled, do this
          ¤
          ¤ end sub
          ¤
          ¤ This begs the question - what is the use of Finally? I had assumed,
          ¤ wrongly as it turns out, that in the event of an exception, Catch and
          ¤ Finally would execute and control would return to the caller. If no
          ¤ exception, Finally would execute and control continues to the next
          ¤ statement.
          ¤
          ¤ I can see no use for Finally!

          Yes, Finally always executes when the flow of control leaves the Try statement. It is an optional
          keyword.

          It guarantees the execution of code in the Finally block if an exception is generated in the Catch
          block or when you execute an Exit Try statement.


          Paul
          ~~~~
          Microsoft MVP (Visual Basic)

          Comment

          • Sean Kirkpatrick

            #6
            Re: Try ... Catch ... Finally confusion

            Paul Clement wrote:[color=blue]
            > ¤ I can see no use for Finally!
            >
            > It guarantees the execution of code in the Finally block if an exception is generated in the Catch
            > block or when you execute an Exit Try statement.
            >[/color]
            Ok, this answer makes some sense - if I'm in a Catch block and *another*
            exception occurs, Finally will ensure that the original cleanup code
            gets called, though I submit that in the case of Exit Try, there is no
            difference between my original examples 2 & 3.

            I'm going to have to play with it a bit to grock it completely.

            Thanks Paul!

            Sean

            Comment

            • david

              #7
              Re: Try ... Catch ... Finally confusion

              On 2005-09-21, Sean Kirkpatrick <nannernanner@c ommunity.nospam > wrote:[color=blue]
              > Paul Clement wrote:[color=green]
              >> ¤ I can see no use for Finally!
              >>
              >> It guarantees the execution of code in the Finally block if an exception is generated in the Catch
              >> block or when you execute an Exit Try statement.
              >>[/color]
              > Ok, this answer makes some sense - if I'm in a Catch block and *another*
              > exception occurs, Finally will ensure that the original cleanup code
              > gets called,[/color]

              Keep in mind that often *another* exception is your own...

              Try
              DoSomething()
              Catch(ex As Exception)
              LogSomeInformat ion(ex.Message)
              Throw
              Finally
              CleanUp()
              End Try

              ....or, something I commonly do...

              Try
              DoSomething()
              Catch(ex as Exception)
              Throw New SpecificExcepti onType(ex)
              Finally
              ....

              [color=blue]
              > though I submit that in the case of Exit Try, there is no
              > difference between my original examples 2 & 3.[/color]

              They are, but that's because you're eating the exception, which should
              be a very, very rare thing. Usually, Try-Finally blocks are much more
              common than Try-Catch blocks..

              Try
              DoSomething()
              Finally
              ' do your cleanup, and let the exception propagate up
              ....

              Comment

              • Cor Ligthert [MVP]

                #8
                Re: Try ... Catch ... Finally confusion

                Sean,

                Know that you can set a try block in a try block

                \\\
                Try
                connection.open
                Try
                do the reading
                Catch
                reader errohandling
                return
                End Try
                Catch
                connection open error handling
                Finally
                connection close 'this will always be done whatever error
                End Try
                ///

                I hope this helps,

                Cor


                Comment

                Working...