Sunday, March 13, 2011

Try Catch block variable access scope


Are the variables declared in  a try block accessible in
the catch block ?
NO. For a variable to be accessible in both try and catch block
it must be declared outside of both blocks.
e.g in the following, variable ut is not accessible in
catch block because it is declared in try block, hence the code will not compile
and will give "Name "ut" is not declared" error

        Try
     Dim ut As New Utility
            Dim dr As DataRow() = x.[Select]("DateTime < '" & DateTime.Now.AddMinutes(-30).ToString("yyyy-MM-dd HH:mm:ss.fff") & "'")
            If dr.Length > 0 Then
                For Each drr As DataRow In dr
                    drr.Delete()
                    ut.WriteLog("C:\test.txt", "Deleted Some Records")
                Next
            End If
        Catch ex As Exception
            ut.WriteLog("C:\test.txt", "Deleted Some Records" + " " + ex.Message)
        End Try

No comments:

Post a Comment