Wednesday, September 14, 2011

Variable Declarations

1. Declare your variables outside of Try / Catch blocks

- AND -

2. Don't initialize your variables in the declaration block.

1 - If you declare your variables inside your Try Catch block you won't be able to access them at exception time.

Sad Code:
Try
 Dim MyString As String

 MyString = "Hey"

Catch ex As Exception
 'Can't view value of MyString here
End Try

Happy Code:
Dim MyString As String

Try
 MyString = "Hey"
Catch ex As Exception
 Response.Write(MyString) 'Yay!
End Try

2 - If you initialize your variables when you declare them, there are two issues.
A - You are creating objects that may never get used
B - Since your declarations are outside the try / catch blocks, you could throw an unhandled exception

Sad Code:
Dim MyObj As New CustomObject() 'Oops, this could cause an error!
Dim MyString As String

Try
 MyString = CInt("Hey") 
'Or it could get thrown out because
'this error happened before it was used

Catch ex As Exception
 'Stuff
End Try

Happy Code:
Dim MyObj As CustomObject 
Dim MyString As String

Try
 MyString = CInt("Hey")
'Now if we get an error here,
'we haven't wasted valuable resources!

 MyObj = New CustomObject()
'Yay! We waited until we needed the object to create it!

Catch ex As Exception
 'Stuff
End Try