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

Category: ASP.NET Questions    |    4 views

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.CreateConnection()
conn.Open()

tr = conn.BeginTransaction()

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.HandleException(ex,
“POLICY_NAME_HERE”)
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

Share/Save/Bookmark

1 Star2 Stars
Loading ... Loading ...

Tags: , , , ,

1 response so far!

Leave a Comment

*
To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
Click to hear an audio file of the anti-spam word