CODING PRACTICE: Returning from function inside a TRY/CATCH block?

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • =?Utf-8?B?U2F2dm91bGlkaXMgSW9yZGFuaXM=?=

    CODING PRACTICE: Returning from function inside a TRY/CATCH block?

    Is it right when placing the RETURN statement inside the TRY or inside the
    CATCH statement, when there is a FINALLY clause? Especially when there is a
    transaction going on, in the try/catch block?

    I give you the following example to meka it more clear:
    (I use Enterprise Library, but the same also applies without it)

    public function f_SomeFunction( parm1,....) as integer
    dim tr as DbTransaction

    Using conn As DbConnection = db.CreateConnec tion()
    conn.Open()

    tr = conn.BeginTrans action()

    try
    ...db action 1
    ...db action 2
    ...db action 3
    tr.Commit()
    return 1

    catch ex as Exception
    tr.Rollback()
    Dim rethrow As Boolean = ExceptionPolicy .HandleExceptio n(ex,
    "POLICY_NAME_HE RE")
    If rethrow Then
    Throw
    End If

    return -1

    finally
    conn.Close()
    end try
    end using
    end function

    Or instead, I should just set a flag variable rather than commiting/rolling
    back (eg. b_ok to TRUE in the TRY clause or FALSE in the CATCH block) and
    then check its value outside the TRY/CATCH block or the Using block and see
    if I should Return 1 or -1?

    I don't know if it's just a matter of programming preference or I could
    sometime get unexpected behavior. Which is the common practice? Any help is
    appreciated

    TIA
    Iordanis
  • Peter Lykkegaard

    #2
    Re: CODING PRACTICE: Returning from function inside a TRY/CATCH block?

    "Savvoulidi s Iordanis" wrote
    Is it right when placing the RETURN statement inside the TRY or inside the
    CATCH statement, when there is a FINALLY clause?
    >
    When ever you have a return statement you are exiting your method
    immediately and the connection is not closed

    - Peter

    Comment

    • George

      #3
      Re: CODING PRACTICE: Returning from function inside a TRY/CATCH block?

      That is incorrrect..

      If you closing your connection inside of Finally block then even if you
      exiting with Return Finally block will run and connection will close...

      George.


      "Peter Lykkegaard" <pl@teklogix.dk wrote in message
      news:u2unNSb6IH A.1428@TK2MSFTN GP06.phx.gbl...
      "Savvoulidi s Iordanis" wrote
      >
      >Is it right when placing the RETURN statement inside the TRY or inside
      >the
      >CATCH statement, when there is a FINALLY clause?
      >>
      When ever you have a return statement you are exiting your method
      immediately and the connection is not closed
      >
      - Peter

      Comment

      • George

        #4
        Re: CODING PRACTICE: Returning from function inside a TRY/CATCH block?

        Your code is perfectly fine except a little confusing.
        If you using "Using" statement then i do not see need to use try/finally
        block. Use one or another. You do not need both. But in your case you want
        to actually catch exception so kill the Using statement.
        Just move tr = conn.BeginTrans action() into try statement.
        So i would rewrite it as follow (I moved tr = conn.BeginTrans action()
        and also checking on tr not beign Nothing befor doing tr.Rollback since
        BeginTransactio n can throw an error and tr will be Nothing

        public function f_SomeFunction( parm1,....) as integer
        dim tr as DbTransaction
        Dim conn As DbConnection = db.CreateConnec tion()
        conn.Open()
        try
        tr = conn.BeginTrans action()
        ...db action 1
        ...db action 2
        ...db action 3
        tr.Commit()
        return 1
        catch ex as Exception
        if( Not tr Is Nothing )
        tr.Rollback()
        Dim rethrow As Boolean = ExceptionPolicy .HandleExceptio n(ex,
        "POLICY_NAME_HE RE")
        If rethrow Then
        Throw
        End If
        return -1
        finally
        conn.Close()
        end try
        end function



        George.


        "Savvoulidi s Iordanis" <SavvoulidisIor danis@discussio ns.microsoft.co mwrote
        in message news:2838406D-6955-466D-A5AF-B65B5C785EB2@mi crosoft.com...
        Is it right when placing the RETURN statement inside the TRY or inside the
        CATCH statement, when there is a FINALLY clause? Especially when there is
        a
        transaction going on, in the try/catch block?
        >
        I give you the following example to meka it more clear:
        (I use Enterprise Library, but the same also applies without it)
        >
        public function f_SomeFunction( parm1,....) as integer
        dim tr as DbTransaction
        >
        Using conn As DbConnection = db.CreateConnec tion()
        conn.Open()
        >
        tr = conn.BeginTrans action()
        >
        try
        ...db action 1
        ...db action 2
        ...db action 3
        tr.Commit()
        return 1
        >
        catch ex as Exception
        tr.Rollback()
        Dim rethrow As Boolean = ExceptionPolicy .HandleExceptio n(ex,
        "POLICY_NAME_HE RE")
        If rethrow Then
        Throw
        End If
        >
        return -1
        >
        finally
        conn.Close()
        end try
        end using
        end function
        >
        Or instead, I should just set a flag variable rather than
        commiting/rolling
        back (eg. b_ok to TRUE in the TRY clause or FALSE in the CATCH block) and
        then check its value outside the TRY/CATCH block or the Using block and
        see
        if I should Return 1 or -1?
        >
        I don't know if it's just a matter of programming preference or I could
        sometime get unexpected behavior. Which is the common practice? Any help
        is
        appreciated
        >
        TIA
        Iordanis

        Comment

        • Peter Lykkegaard

          #5
          Re: CODING PRACTICE: Returning from function inside a TRY/CATCH block?

          "George" skrev
          That is incorrrect..
          >
          Ok thanks for the correction :)

          - Peter

          Comment

          • Peter Lykkegaard

            #6
            Re: CODING PRACTICE: Returning from function inside a TRY/CATCH block?

            "George" skrev
            That is incorrrect..
            >
            Ok thanks for the correction :)

            - Peter

            Comment

            • Mark Stevens

              #7
              Re: CODING PRACTICE: Returning from function inside a TRY/CATCH block?

              On Sat, 19 Jul 2008 12:27:16 -0400, "George" <noemail@comcas t.net>
              wrote:
              >If you using "Using" statement then i do not see need to use try/finally
              >block. Use one or another. You do not need both. But in your case you want
              Correct me if I am wrong, but doesn't "using" tell the run-time system
              to release any resources as soon as possible? This is a little
              different from using the finally block to close the connection.

              Also, in answer to the original poster, it is often considered good
              style to only have one exit point from a method.

              Regards
              Mark
              --
              |\ _,,,---,,_ A picture used to be worth a
              ZZZzzz /,`.-'`' -. ;-;;, thousand words - then along
              |,4- ) )-,_. ,\ ( `'-' came television!
              '---''(_/--' `-'\_)

              Mark Stevens (mark at thepcsite fullstop co fullstop uk)

              This message is provided "as is".

              Comment

              • Mark Rae [MVP]

                #8
                Re: CODING PRACTICE: Returning from function inside a TRY/CATCH block?

                "Mark Stevens" <nevyn@nospam.n ospamwrote in message
                news:96v5841g56 1rl9en13ms5tn3l b8ets68hs@4ax.c om...
                >If you using "Using" statement then i do not see need to use try/finally
                >block. Use one or another. You do not need both. But in your case you
                >want
                >
                Correct me if I am wrong, but doesn't "using" tell the run-time system
                to release any resources as soon as possible? This is a little
                different from using the finally block to close the connection.
                It largely depends what the Try...Finally is used for. However, a Using
                block and a Try...Finally construction are most certainly *not* mutually
                exclusive. See here straight from the horse's mouth, as it were:

                Also, in answer to the original poster, it is often considered good
                style to only have one exit point from a method.
                Yes, but only by people for whom such coding aesthetics are more important
                than what the code actually does...


                --
                Mark Rae
                ASP.NET MVP


                Comment

                • =?ISO-8859-1?Q?G=F6ran_Andersson?=

                  #9
                  Re: CODING PRACTICE: Returning from function inside a TRY/CATCH block?

                  Mark Stevens wrote:
                  On Sat, 19 Jul 2008 12:27:16 -0400, "George" <noemail@comcas t.net>
                  wrote:
                  >
                  >If you using "Using" statement then i do not see need to use try/finally
                  >block. Use one or another. You do not need both. But in your case you want
                  >
                  Correct me if I am wrong, but doesn't "using" tell the run-time system
                  to release any resources as soon as possible?
                  No, it disposes the object at the end of the using block, not sooner.
                  This is a little
                  different from using the finally block to close the connection.
                  No, a using block is just syntactic sugar for a try...finally, so there
                  is actually no difference at all.
                  Also, in answer to the original poster, it is often considered good
                  style to only have one exit point from a method.
                  >
                  Regards
                  Mark

                  --
                  Göran Andersson
                  _____
                  Göran Anderssons privata hemsida.

                  Comment

                  Working...