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.
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
.
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.
Yes. rename the variable causing the problem to a unique name.
来源:https://stackoverflow.com/questions/3389394/variable-variablename-hides-a-variable-in-an-enclosing-block