Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is Try/Catch/finally required with the Using statement in order to handle exceptions?

I wonder how to use statement handles exceptions? Do I need to wrap the using statements with a Try/Cath/Finally clause in order to be sure that the SqlConnection object is closed and disposed even if the containing code throws an exception?

Public Function GetUserAccountKeyByUsername(ByVal pUsername As String) As Int32
    If String.IsNullOrEmpty(pUsername) Then
        Throw New ArgumentNullException("pUsername", "Username is missing")
    End If

    Dim o As Object
    Dim userAccountKey As Int32
    Dim SQL As StringBuilder = New StringBuilder()

    With SQL
        .Append("SELECT USER_KEY ")
        .Append("FROM USER ")
        .Append("WHERE USERNAME = @Username ")
    End With

    Try
        Using conn As SqlConnection = New SqlConnection(ConnectionString)
            conn.Open()
            Using cmd As SqlCommand = New SqlCommand(SQL.ToString, conn)
                Try
                    cmd.CommandTimeout = Convert.ToInt32(ConfigurationManager.AppSettings("SQLQueryLimitTime"))
                    cmd.Parameters.Add(New SqlParameter("@Username", SqlDbType.VarChar)).Value = pUsername
                    o = cmd.ExecuteScalar()
                    If (o IsNot Nothing) AndAlso Not (IsDBNull(o)) Then
                        userAccountKey = Convert.ToInt32(o)
                    End If
                Catch ex As Exception
                    _log.logError(ex, cmd)
                End Try
            End Using
        End Using
    Catch ex As Exception
        _log.logError(ex, conn.ConnectionString)
    Finally
        conn.Close()
        conn.Dispose()
    End Try
    Return userAccountKey
End Function
like image 868
Jonas Avatar asked Jan 31 '12 09:01

Jonas


People also ask

Does try finally catch exceptions?

That is, you can catch the exception in the method that calls the method that contains the try - finally statement, or in the method that calls that method, or in any method in the call stack.

What is the purpose of using try catch finally statement?

The try statement defines the code block to run (to try). The catch statement defines a code block to handle any error. The finally statement defines a code block to run regardless of the result.

What is try catch finally exception handling?

The code that will possibly throw an exception is enclosed in the try block and catch provides the handler for the exception. The finally block executes the code enclosed in it regardless of whether the exception is thrown or not. The finally block generally follows the try or try-catch block.

What happens if a try catch finally statement does not have a catch clause to handle an exception that is thrown within the body of the try statement?

If an exception is thrown from the try block, even when there's no catch block to handle the exception, the finally block still executes, in which case the exception is still thrown immediately after the finally block finishes executing. The following example shows one use case for the finally -block.


1 Answers

using puts try and finally in your code and automatically it calls .Dispose() and eventually .Close() coz DbConnection.Dispose() calls Close(), but there is no catch, so you will need to add catch over using block, some thing like this

try
{
   using(some resource)
   {
   }
}
catch(Exception)
{
}

vs

try
{
}
catch(Exception)
{
}
finally{ }

So looking at this you might think Try/Catch/Finally is better than Using, coz in using in any case you need to handle error, but it's not.

If there is any error during .Close() or .Dispose() occurs, the first sample will handle that too, but in second case you will have to put try-catch in finally block.

Read more about Avoiding Problems with the Using Statement (MSDN)

Hope this answers your question.

like image 126
Amar Palsapure Avatar answered Nov 10 '22 17:11

Amar Palsapure