views:

29

answers:

2

When copying and pasting a bit of sample code from MSDN, I came up with the error in the title - Variable '' hides a variable in an enclosing block,

All I copied was a very basic example of a try loop.

As it says in the suggestion "A common cause for this error is the use of Catch e As Exception inside an event handler. If this is the case, name the Catch block variable ex rather than e."

So, I did that, changed both e to ex and it worked, however, I don't understand why this doesn't cause the same error.

Can someone please explain better what the error is and why e causes it, and ex doesn't?

edit -

code example...

    Try
    Catch e As Exception
        msgbox(e.Message)
    End Try

.

    Try
    Catch ex As Exception
        msgbox(ex.Message)
    End Try

What I don't understand is why the first one causes the problem and the second one doesn't, to me, it is like... Using apples above, apple below - saying you can't use the same thing in both places, then changing both to oranges and suddenly letting it work. Surely the second is doing the same as the first.

+3  A: 

You might want to paste the full code for the error to confirm but I would assume that the event handler defines a parameter called "e". Then when you put in the catch block it tries to define "e" as well, causing the error in question. Of course when the catch is defining "ex" instead of "e" then there is no name clash happening so it works.

Edit: Edited to add clearer example of what I assume is the breoken code.

I assume your breaking code looks like:

Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
    Try
    Catch e As Exception
        msgbox(e.Message)
    End Try
End Sub

You can see the two declarations of e, one in ByVal e As System.EventArgs and the other at Catch e As Exception.

Chris
+1 - Many thanks and marking as answer... Brilliant, Seems so easy now and I can't believe I missed this! This is exactly what it is!... Seems so simple now!
Wil
This is why its always worthwhile pasting full code. You might not think its necessary but you also don't know what's wrong so other people asking for it is generally at least worth asking "Which bit in particular" (if you think there is too much to paste it all). And thanks for getting me past 1k rep. ;-)
Chris
+3  A: 

That error message means that you are declaring a variable with a name that already exists:

int abc = 0;
if (abc == 0)  {
  int abc = 1;  // Error
}

This rule applies of course to try .. catch as well.

dark_charlie
+1 Many thanks.
Wil