הערה
הגישה לדף זה מחייבת הרשאה. באפשרותך לנסות להיכנס או לשנות מדריכי כתובות.
הגישה לדף זה מחייבת הרשאה. באפשרותך לנסות לשנות מדריכי כתובות.
Question
Saturday, November 1, 2014 4:55 PM
Hello, a bit new to visual basic. Still learning stuff. Right now, I'm learning about Try Catch Statements.
I'm trying to code a Try Catch Statement that allows only string in a certain textbox. Am I on the right track? Or doing it completely wrong?
Dim usertext As String
usertext = Textbox1.Text
Try
If usertext = true Then
'Confused what to put here.
ElseIf usertext = False Then 'If usertext is not string type, then an error occurs
MessageBox.Show("Please enter valid text.", "ERROR!", MessageBoxButtons.OK, MessageBoxIcon.Error)
Catch ex As ArgumentException
String.IsNullOrEmpty(usertext) 'If no text is entered display an error message
MsgBox("Please enter some text within the indicated field.", MsgBoxStyle.Critical, "ERROR!")
End Try
All replies (23)
Saturday, November 1, 2014 5:35 PM ✅Answered
Hello, a bit new to visual basic. Still learning stuff. Right now, I'm learning about Try Catch Statements.
I'm trying to code a Try Catch Statement that allows only string in a certain textbox. Am I on the right track? Or doing it completely wrong?
Dim usertext As String
usertext = Textbox1.Text
Try
If usertext = true Then
'Confused what to put here.
ElseIf usertext = False Then 'If usertext is not string type, then an error occurs
MessageBox.Show("Please enter valid text.", "ERROR!", MessageBoxButtons.OK, MessageBoxIcon.Error)
Catch ex As ArgumentException
String.IsNullOrEmpty(usertext) 'If no text is entered display an error message
MsgBox("Please enter some text within the indicated field.", MsgBoxStyle.Critical, "ERROR!")
End Try
There are other ways to do that: One is using validation and another way is using something like Kevin posted, but since your question is about structured exception handling, here's an outline of how you could do that:
In the TextBox's .Leave event, set up a For Each loop for each character in the string. The For Each loop should be shrouded within a Try/Catch (please do NOT leave the Catch empty!), then per character you could then test it using Char.IsDigit which returns a boolean.
If it returns True, then throw an exception which will then be handled by your Try/Catch.
Still lost in code, just at a little higher level.
:-)
Saturday, November 1, 2014 5:45 PM ✅Answered
Using Try-Catch is possible but reckless and improper usage of Try-Catch. Rule of thumb is
- Use assertion first i.e. before opening a file, see if it exists
- Before working on text see if there is any
- etc
If there is no safe way to use assertion then use an unhandled application exception handler, let it capture the exception. Now a) fix the problem b) figure out assertion to not cause it again.
If the exception happens seldom a Try-Catch is okay
Here are some examples I put together, using try-catch and then using assertion
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Try
CType(sender, ListBox).Items.Add("Bad")
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
If TypeOf sender Is ListBox Then
CType(sender, ListBox).Items.Add("Bad")
Else
MessageBox.Show("sender is a " & sender.GetType.ToString)
End If
Dim FileName As String = IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Nothere.txt")
Dim Lines As String() = {}
Try
Lines = IO.File.ReadAllLines(FileName)
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
If IO.File.Exists(FileName) Then
Lines = IO.File.ReadAllLines(FileName)
Else
MessageBox.Show(FileName & " does not exist")
End If
End Sub
I can not stress enough that try-catch is a last resort that you have exhausted all other options.
Caveat: Sometimes a exception may be lost in a Form load event so we can use (from the IDE menu) Debug ->Exception, check "common language runtime exceptions" and when the exception is found go thru the steps of "how can I prevent this w/o try-catch)
Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem.
Saturday, November 1, 2014 5:10 PM
Hello,
No need for a Try-Catch. The code below allows a-z and separator (space), not numbers. Look at the Char class for more methods.
If Not String.IsNullOrWhiteSpace(TextBox1.Text) Then
Dim CharTest As Boolean = False
For Each c As Char In TextBox1.Text
If Char.IsSeparator(c) Then
Continue For
ElseIf Not Char.IsLetter(c) Then
CharTest = True
Exit For
End If
Next
If CharTest Then
MessageBox.Show("Text can not contains anything other than a-z")
Exit Sub
End If
MessageBox.Show(String.Format("'{0}'", TextBox1.Text))
Else
MessageBox.Show("Please enter something")
End If
Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem.
Saturday, November 1, 2014 5:31 PM
This looks like a great solution, but I would really like a solution using a Try Catch as I am learning about those as of late. I could easily convert this to a try catch right?
Saturday, November 1, 2014 5:41 PM
Thinking this out a bit more though, what you're asking to may not be practical - at least not as you asked it.
What if the string is "123 Elm Street"?
That's a legitimate string, so instead of testing each character in a loop, test the entire string using Double.TryParse. You can use other numeric TryParse methods if you want, that's just the first one to come to mind.
If the entire string CAN be parsed (cast, actually) to a type double, THEN throw the exception. The example string above would NOT pass muster so it's safely then a string which just happens to have a number in it.
Still lost in code, just at a little higher level.
:-)
Saturday, November 1, 2014 5:47 PM
Using Try-Catch is possible but reckless and improper usage of Try-Catch.
What?!?
Nonsense ... total and complete nonsense.
Still lost in code, just at a little higher level.
:-)
Saturday, November 1, 2014 5:48 PM
@Frank, I considered the same thing a-z, 0-9 etc (good point). To me MomochiLL needs to clarify this.
Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem.
Saturday, November 1, 2014 5:58 PM
I didn't consider string like addresses. Hmm... you bring up a good point!
Frank, I think I will attempt your solution and see how it goes. Thank you for adhering to my question.
Saturday, November 1, 2014 6:04 PM
I didn't consider string like addresses. Hmm... you bring up a good point!
Frank, I think I will attempt your solution and see how it goes. Thank you for adhering to my question.
Give it a try (no pun intended) and see how it goes.
Please be sure that Option Strict is set to ON, and please do NOT leave an empty Catch.
*****
If you get stuck, then post that routine using the code block tool in this forum, and let's see what you have.
:)
Still lost in code, just at a little higher level.
:-)
Saturday, November 1, 2014 6:46 PM
Okay, I made a quick test button, which seems to work decently.
Private Sub Button8_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button8.Click
Dim usertext As String
usertext = TextBox1.Text
Try
If IsNumeric(usertext) Then
MessageBox.Show("Please enter only letters.")
ElseIf usertext = String.Empty Then
MessageBox.Show("Please enter some text.")
End If
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
End Class
Now I will attempt just a reg statement to catch all possible errors.
Saturday, November 1, 2014 7:08 PM
In full respect of Frank, Kevin is in my opinion right. Not with his samples but with his text.
The Try Catch is a last possibility to take if no other ways are possible to check if something is not true.
For instance you can check if something is numeric, but not if a SQL server is available or that simply the power of that is unplugged.
Be aware that a try catch takes more time than billions times a calculation if there is an exception.
Success
Cor
Saturday, November 1, 2014 7:29 PM
In full respect of Frank, Kevin is in my opinion right. Not with his samples but with his text.
The Try Catch is a last possibility to take if no other ways are possible to check if something is not true.
For instance you can check if something is numeric, but not if a SQL server is available or that simply the power of that is unplugged.
Be aware that a try catch takes more time than billions times a calculation if there is an exception.
Success
Cor
If you have a specific "test" for something, then there's nothing wrong with using structured Exception handling and in fact, throwing an exception if it doesn't pass the test.
Still lost in code, just at a little higher level.
:-)
Saturday, November 1, 2014 7:39 PM
No it is done in fact in the TryCast, however in those there are no other reasonable possibilities.
However, if there are better and faster way available then take those.
Success
Cor
Saturday, November 1, 2014 7:51 PM
Okay, I made a quick test button, which seems to work decently.
Private Sub Button8_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button8.Click
Dim usertext As String
usertext = TextBox1.Text
Try
If IsNumeric(usertext) Then
MessageBox.Show("Please enter only letters.")
ElseIf usertext = String.Empty Then
MessageBox.Show("Please enter some text.")
End If
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
End ClassNow I will attempt just a reg statement to catch all possible errors.
In compliance with what this thread is about - using structured exception handling - the following shows a routine that will do that:
Option Strict On
Option Explicit On
Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, _
ByVal e As System.EventArgs) _
Handles MyBase.Load
' Used to initialize anything that needs
' to be initialized...
End Sub
Private Sub TextBox1_Leave(ByVal sender As Object, _
ByVal e As System.EventArgs) _
Handles TextBox1.Leave
Try
If TextBox1.Text.Trim <> "" Then
If Integer.TryParse(TextBox1.Text, New Integer) Then
Throw New ArgumentException("The entry must be strictly text.")
End If
End If
Catch ex As Exception
MessageBox.Show("An error occurred:" & vbCrLf & vbCrLf & ex.Message, _
"Input Error", MessageBoxButtons.OK, MessageBoxIcon.Warning)
End Try
End Sub
End Class
To test it:
But the following one allows it:
If you'll give me about 20 minutes though, I'll show you another way that you can do this...
Still lost in code, just at a little higher level.
:-)
Saturday, November 1, 2014 8:03 PM
Okay, I made a quick test button, which seems to work decently.
Private Sub Button8_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button8.Click
Dim usertext As String
usertext = TextBox1.Text
Try
If IsNumeric(usertext) Then
MessageBox.Show("Please enter only letters.")
ElseIf usertext = String.Empty Then
MessageBox.Show("Please enter some text.")
End If
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
End ClassNow I will attempt just a reg statement to catch all possible errors.
This is another way that it can be done which doesn't use (nor does it need) exception handling. It still allows the user to type anything they want, but when they leave the control, it won't let them get away with it if it doesn't pass the test:
Option Strict On
Option Explicit On
Public Class Form1
Private ep As New ErrorProvider
Private Sub Form1_Load(ByVal sender As System.Object, _
ByVal e As System.EventArgs) _
Handles MyBase.Load
Button1.Enabled = False
End Sub
Private Sub TextBox1_TextChanged(ByVal sender As System.Object, _
ByVal e As System.EventArgs) _
Handles TextBox1.TextChanged
ep.Clear()
If TextBox1.Text.Trim <> "" Then
Button1.Enabled = True
Else
Button1.Enabled = False
End If
End Sub
Private Sub TextBox1_Validating(ByVal sender As Object, _
ByVal e As System.ComponentModel.CancelEventArgs) _
Handles TextBox1.Validating
If TextBox1.Text.Trim <> "" Then
Dim sb As New System.Text.StringBuilder
If Integer.TryParse(TextBox1.Text, New Integer) Then
sb.AppendLine("The entry must be text only.")
sb.AppendLine()
sb.AppendLine("Please modify your entry or")
sb.AppendLine("clear this text area entirely")
sb.AppendLine("in order to continue.")
ep.SetError(TextBox1, sb.ToString)
e.Cancel = True
Button1.Enabled = False
End If
End If
End Sub
End Class
As before, the following works just fine though:
This last example uses the .Validating event and an error provider. It's a better way than the first, in my opinion, because it's less intrusive and because it allows you to "lock the user in" until they correct it.
The drawback to setting e.Cancel to true is that they can't even close the program until they correct it, which is dangerous - if you'll notice the logic in what I just posted though, you'll see that if they just clear the text from the TextBox, they can proceed ... but then if they do that, Button1 will be disabled so they still can't actually proceed.
I hope this might give you some thoughts.
Still lost in code, just at a little higher level.
:-)
Saturday, November 1, 2014 8:03 PM
Frank,
What do you mean with this, in fact your sample shows what Kevin and I wrote, the Try and catch is complete seleseles because it will never catch an error. I only see the message done by the trycast not by the try and catch.
Success
Cor
Saturday, November 1, 2014 8:06 PM
Frank,
What do you mean with this, in fact your sample shows what Kevin and I wrote, the Try and catch is complete seleseles because it will never catch an error. I only see the message done by the trycast not by the try and catch.
Success
Cor
What do I mean by what?
We don't all see this forum the same way. Please be specific.
Still lost in code, just at a little higher level.
:-)
Saturday, November 1, 2014 8:45 PM
What do I mean by what?
We don't all see this forum the same way. Please be specific.
Funny Frank, to use what I sometimes write but then are called offending.
However, this thread is about if the Try and Catch End Try is really always needed.
In your last sample the Catch does in my opinion deserve anything more than a waste of code. The problem is already catched by the Trycatch (which is in fact a Try Catch End Try behind the scene and therefore in my opinion not such a nice sample) between the parenthesis euphorisch said.
Success
Cor
Saturday, November 1, 2014 8:56 PM
@Cor:
I have removed my last reply because it's going off at a tangent and it's beyond the scope of the OP's question.
We'll just have to agree to disagree on this.
Still lost in code, just at a little higher level.
:-)
Saturday, November 1, 2014 9:12 PM
Hello, a bit new to visual basic. Still learning stuff. Right now, I'm learning about Try Catch Statements.
I'm trying to code a Try Catch Statement that allows only string in a certain textbox. Am I on the right track? Or doing it completely wrong?
Dim usertext As String
usertext = Textbox1.Text
Try
If usertext = true Then
'Confused what to put here.
ElseIf usertext = False Then 'If usertext is not string type, then an error occurs
MessageBox.Show("Please enter valid text.", "ERROR!", MessageBoxButtons.OK, MessageBoxIcon.Error)
Catch ex As ArgumentException
String.IsNullOrEmpty(usertext) 'If no text is entered display an error message
MsgBox("Please enter some text within the indicated field.", MsgBoxStyle.Critical, "ERROR!")
End Try
Just to have this on the record, let me explain my perception of what this debate is about:
Let's say that you have a routine which uses a file. You obviously need to be sure that the file exists so there are a few ways you can do that:
First, you can test that it exists and, if not, then show a message or log it and return nothing, or whatever is appropriate. That's the most direct way to go about it.
On the other hand, you can test that it exists and if not, throw an exception inside a Try/Catch.
The second way is going about it "the long way", and no it's not what I'd do -- but does it therefore make the WRONG way?
I contend that while it may not be the shorter way, that there's nothing actually WRONG with doing it. That's what this ordeal is about and I apologize if it's caused you to become confused by it.
Still lost in code, just at a little higher level.
:-)
Sunday, November 2, 2014 5:39 AM
This looks like a great solution, but I would really like a solution using a Try Catch as I am learning about those as of late. I could easily convert this to a try catch right?
If you use option strict on in your code then if you try to place a non string type into a textbox you should be shown an error in your code.
Why would you need a try/catch for that?
TextBox's display strings. So if you perform appropriate conversions on other datatypes such as integer or object then you will not have any issue. That requires appropriate coding techniques.
And if you don't want to learn appropriate coding techniques then using a try/catch to handle exceptions to proper coding techniques is a pretty useless method for coding.
So if I created a List of String (Dim Temp As New List(Of String)) and added something to it (Temp.Add("Hello") and then coded "TextBox1.Text = Temp" I don't think using a Try/Catch to determine I don't know what I'm doing is really a valid method for not learning how to do what I should know how to do prior to coding something that stupid. Although with Option Strict On being used I would definitely be notified that what I'm trying to do is invalid and why it's invalid.
La vida loca
Sunday, November 2, 2014 6:09 AM
Monkeyboy...I did include in my original post that I am NEW TO VISUAL BASIC CODING. Your post comes off as really rude, and I don't appreciate that at all. I am taking a class, and specifically stated, we are learning about try catch statements. Sorry that I don't know much yet.
Thanks to everyone else who provided useful information.
Sunday, November 2, 2014 6:21 AM
If you want to practice Try...Catch...Finally Statement (Visual Basic) then try doing it on something that makes sense. So you can learn how to use it correctly.
La vida loca