Variable hides a variable in an enclosing block [duplicate] - vb.net

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.

Related

Not catching exceptions even though it is inside try catch?

I am deleting a row inside a DataGridView and when there is no more row this pops up.
Private Sub materialsGridView_SelectionChanged(sender As Object, e As EventArgs) Handles materialsGridView.SelectionChanged
Try
materialSelectedindex = materialsGridView.CurrentRow.Index
Catch ex As Exception
materialSelectedindex = -1
End Try
End Sub
Private Sub delRowBtn_Click(sender As Object, e As EventArgs) Handles delRowBtn.Click
If (materialSelectedindex = -1) Then
MsgBox("Please select a row")
Return
End If
materialsGridView.Rows.RemoveAt(materialSelectedindex)
End Sub
Here is an image
Why is it not catching even though it is inside a try catch?
Look at the Exception Assistant window. See how the box is checked that says "Break when this exception type is thrown"? If you don't want the debugger to break when that exception type is thrown, uncheck that box. That is only happening because you're running in the debugger. If you run the application without debugging, which you can do either directly or using the VS toolbar or pressing Ctrl+F5, then the exception will be caught.
By the way, it's generally bad practice to catch the base Exception type. You should catch only the specific exceptions that you reasonably believe could be thrown. Otherwise, you might be allowing a situation that you didn't count on and which might end up causing data corruption or the like.
You should also generally avoid exceptions being thrown in the first place, by validating the data you intend to use. In your case, you should check whether CurrentRow is Nothing first and then only use it if it's not. You could do this:
materialSelectedIndex = If(materialsGridView.CurrentRow Is Nothing,
1,
materialsGridView.CurrentRow.Index)
or you could do this:
materialSelectedIndex = If(materialsGridView.CurrentRow?.Index, 1)
The first option is basically an If...Then...Else while the second option uses the first value unless it's Nothing, in which case it uses the second value. The ?. operator will stop evaluation of the expression if what precedes it is Nothing, otherwise it behaves like a regular . operator.

Can I catch all possible errors with one message? Vb.net

The project I'm working on is almost ready to ship. Occasionally, I'll encounter an error that won't allow the program to continue running like an out of bounds or a memory limitation.
These kinds of errors
I've been fixing them as I find them, but I'm sure there are others. However, I'm leaving this position in a few days so I need the users to not encounter these.
Is there a way in Vb.net that anytime one of those errors wants to pop up, it can catch it with an message box to the user that says something like "Something really bad happened. Please restart program"?
If it's a winform, you can catch the errors by handling the Application.ThreadException event.
AddHandler Application.ThreadException, AddressOf UIThreadException
Private Shared Sub UIThreadException(ByVal sender As Object, ByVal t As ThreadExceptionEventArgs)
' Handle event here and show message
' Exception is in t.Exception
End Sub
Make sure there's no error in this error handler. I don't think it'll catch exception in other threads.
You can use the Try statement, which is a simple way to handle error.
Here is a simple example:
Try
'Do something
Catch ex As Exception
MsgBox("Error occured")
End Try

Repeated error handling

So in my vb.net application, i've got alot of try and catch blocks for error handling, especially whenever my app talks to the db.
i'm running through a series of if/elseif statements to see if
ex.tostring.contains("Unable to connect to any of the specified MySQL hosts")
and various bits like that.
At the minute, I wrote this out and copy and pasted it into each catch, but I know there will be a much more efficient way to do this whereby the code is just in one place and called as and when required.
I tried to implement it as a function, but I had trouble passing info to the function.
So i thought I'd ask and see how you guys go about doing this?
You don't need multipe try...catch statements for a program. One is enough.
If i understood you correctly, you want to print or show the error that occured inside the Try block.
Public Sub main()
Try
'Do something
Catch ex As Exception
End Try
Try
'Do something else
Catch ex As Exception
End Try
If ex.tostring.contains("something") than
End Sub
Instead you can do something like this:
Public Sub main()
Try
'Do all your code here.
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
In this part, the compiler will automaticlly print the error occured in the program.
You can perform some action based on the type of exception thrown. Checking the text if not recommended as this could change with a new version of .net or mysqldata
Try something like this:
Try
'
' Programming lines of code
'
Catch exError As MySqlException
' an error occurred with MySql
Catch e As Exception
' a General error occurred
Finally
' Cleanup custom and unmanaged resources if necessary
End Try
Have a look at the MySQL Documentation for their recommendations

How to implement a Try/Catch block in a form [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I have created a form for student-course registration that has three entry text boxes:
Name and surname
Phone number
Address
I then have another text box that I use to display the student information. I call this display-only text box the "course" text box.
I want to make use of structured exception handling (Try/Catch block) on this form. How can I do that on this kind of a form.
Exception Handling with Try/Catch
Exception handling in VB.Net is very easy. The following code is the structure of the try/catch block.
Try
'This is the code you wish to try that might give an error.
Catch ex As Exception
'This is where you end up if an error occurs.
End Try
Lets say you have a button on your form and you want to make sure that after the button is pressed, all the instruction you have will be error handled properly. The following code illustrates. First drop a button and name it ValidationButton. If you double click your new button, in the code behind you will see a new function that handles the click event. Add the try catch block to it as seen below.
Private Sub ValidationButton_Click(sender As System.Object, e As System.EventArgs) Handles ValidationButton.Click
Try
Catch ex As Exception
End Try
End Sub
Now the page has a button and the code inside it is in a try/catch block. We simply put the code we want inside. Lets put something that will throw and error, and then we will display that error.
Example Code
Private Sub ValidationButton_Click(sender As System.Object, e As System.EventArgs) Handles ValidationButton.Click
Try
Dim x As Integer = 1
Dim y As Integer = 0
Dim z As Integer = x / y
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
A message box pops up telling us that we encountered an error, "Arithmetic operation resulted in an overflow". This is ofcourse because we cannont divide by zero. If you had not placed this in the try catch, the program would have crashed.
So, with this information, put your try/catch in places where you could possibly have an error. If you know what your error might be, you can even have code in there to do something else. In our example, we might want to tell the user not to divide by zero.
In addition to catching errors in specific lines of code, you can also catch unhandled errors. This is easiest done by starting the application through the Main Procedure
Module Program
Public Shared Sub Main()
AddHandler Application.ThreadException, AddressOf UIThreadException
' Force all Windows Forms errors to go through our handler.
Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException)
' Start the main Form
Application.Run(New frmMain())
End Sub
Private Shared Sub UIThreadException(ByVal sender As Object, _
ByVal t As ThreadExceptionEventArgs)
' Handle the error here
End Sub
End Module
You can read more on this subject on MSDN: Application.ThreadException Event

Object Reference not set to an instance of an object

I have a form which has a search feature - a single text field and command button; when the text field is filled-in a database query is executed and the result (if one result returned) is shown on the form via dynamic control fields.
When the search feature is used for the first time, the fields are created and the data is returned from the database, however when the search feature is re-ran I am getting the error "Object Reference not set to an instance of an object", the error occurs at:
initSearch(txtSearchInput.Text)
I am guessing that I am not handling the textfield properly for this type of use, can anyone please advise how else I should be doing this?
The txtSearchInput is not a dynamic field, it has been created through the design mode, the same for the command button. The above code is located in the command button On Click event:
Private Sub btnGo_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnGo.Click
Try
initSearch(txtSearchInput.Text)
Catch ex As Exception
MsgBox(ex.Message, MsgBoxStyle.Critical, "Error Encountered")
End Try
End Sub
Any help would be greatly appreciated.
Thanks,
Matt
Any help would be greatly appreciated.
The error is not in the code you posted. The Text property of a TextBox, and the reference to a Form Textbox don't become null all of a sudden.
You probably have to debug into initSearch
Did you test in the debugger if txtSearchInput is null?
Exception could be bubbling up from initSearch function, best way is to debug your code.