|
-
Feb 9th, 2012, 11:33 AM
#1
Thread Starter
New Member
Beginner: TRY and CATCH fonctions nothing catches
Hi, I am trying to get TRY and CATCH fonctions to work, but nothing is catching, here is what I have done (note I am new to VB)...
In my textbook I have a sample:
vb.net Code:
Try
monthlyInvestmenmt = convert.ToDecimal(txtMonthlyInvestment.Text)
YearlyInterestRate = Convert.ToDecimal(txtInterestRate.Text)
years = convert.ToInt32(txtYears.Text)
Catch ex As FormatException
messageBox.Show("A format exception has occurred. Plse check all _
entries.")
End Try
-----my code below...
Now according to my instructions I must start the debugging to obtain the exception, but nothing will catch using my code, it just goes thru as it was meant to be...???
vb.net Code:
Try
Catch ex As Exception
If txtCurrValue.Text = "" Or txtRate.Text = "" Or txtPeriods.Text = ""
Then MessageBox.Show("Plse ensure all required field are complete")
Exit Sub
End If
Else
dblRate = TxtRate.Text
MessageBox.Show(ex.Message & vbCrLf & vbCrLf & ex.StrackTrace, _
ex.GetType.ToString)
End Try
-------
When running the code it works fine, do I have to create an error for the code to catch it, and if nothing catches how do I know that the Try Catch functions worked?
I know it is basic, but that process is not clear to me, even after reading about it. Tks for your help.
Last edited by Hack; Feb 9th, 2012 at 11:49 AM.
-
Feb 9th, 2012, 12:11 PM
#2
Re: Beginner: TRY and CATCH fonctions nothing catches
Try to parse a value of ABC and see. You should get an error. Also, the second box of code you have in your post should be within the first Catch like this:
Code:
Try
monthlyInvestmenmt = convert.ToDecimal(txtMonthlyInvestment.Text)
YearlyInterestRate = Convert.ToDecimal(txtInterestRate.Text)
years = convert.ToInt32(txtYears.Text)
Catch ex As FormatException
messageBox.Show("A format exception has occurred. Plse check all _
entries.")
End Try
One other tidbid -- unless you plan on getting screen shots of the error from remote users, the stack trace in your error message will be mostly useless to the end user.
Last edited by mbutler755; Feb 9th, 2012 at 05:18 PM.
Reason: Last time I copy & paste -- Promise!
-
Feb 9th, 2012, 12:14 PM
#3
Re: Beginner: TRY and CATCH fonctions nothing catches
Welcome to VBForums 
 Originally Posted by mrspock3333
... do I have to create an error for the code to catch it, and if nothing catches how do I know that the Try Catch functions worked?
Yes you would need an error to see those code-lines beeing done, that's what you told the code to do, Try this code (in your example NO Code), if it works that's fine, if it raises an error Iit will be "catched".
You're welcome to rate this post!
If your problem is solved, please use the Mark thread as resolved button
Wait, I'm too old to hurry!
-
Feb 9th, 2012, 12:18 PM
#4
Re: Beginner: TRY and CATCH fonctions nothing catches
The idea is to put the code you want to safeguard in the Try clause (between Try and Catch). The Catch clause (between Catch and End Try) says what to do if an exception occurs in the Try clause. If there's nothing in the Try clause, then nothing can go wrong with it can it ?
The code you have at present on lines 3-6 validates the text boxes. As far as I can seen there is no way that could raise an exception, so there's no point in putting it in a Try clause. In fact, with your present code you don't need Try/Catch at all. The purpose of Try/Catch is to deal with situations you can't predict.
BB
-
Feb 10th, 2012, 08:46 AM
#5
Thread Starter
New Member
Re: Beginner: TRY and CATCH fonctions nothing catches
Thank you Opus for your welcome to the forum. This is great!
-
Feb 10th, 2012, 08:48 AM
#6
Thread Starter
New Member
Re: Beginner: TRY and CATCH fonctions nothing catches
Thank you all, mbutler755 I will review my code, thanks.
-
Feb 10th, 2012, 10:13 AM
#7
Thread Starter
New Member
Re: Beginner: TRY and CATCH fonctions nothing catches
Okay, it worked! ;-)
I am unshure why, but what I have done differently this time was to put my TRY statement before the Declaration of variables and it worked, does that makes sense?
If so, when using TRY/Catch do you have to only include your TRY and Catch between the required variables in order to trigger the Exception wanted, keep in mind that I am experimenting with the function at this time.
Also, the exception that I found was an InvalidCastException. When you use the word Exception i.e. ...
Catch ex As Exception
...am I right to say that the Code word Exception will find all types of exceptions and that a specific exception i.e. ...
Catch ex As InvalidCastException
...will only catch this type? Thanks in advance, this forum is great!
-
Feb 10th, 2012, 10:17 AM
#8
Re: Beginner: TRY and CATCH fonctions nothing catches
Hello,
I would suggest using assertion to determine if a string value can be used as a numeric rather than have an exception raised.
As per above we first check to see if all items can be converted to Decimal and Integer. From here you should consider if needed do all numeric values fall into a specific range i.e. if a variable can be 10 to 20 and nothing else you should check for this.
Code:
If Decimal.TryParse(txtMonthlyInvestment.Text, monthlyInvestmenmt) AndAlso
Decimal.TryParse(txtInterestRate.Text, YearlyInterestRate) AndAlso
Int32.TryParse(txtYears.Text, years) Then
MessageBox.Show("A format exception has occurred. Plse check all entries.")
End If
Another use of assertion trying to cast sender which is of type Object but can be cast as a Button not a ListBox.
Code:
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
If sender.GetType Is GetType(ListBox) Then
DirectCast(sender, ListBox).Items.Clear()
Else
MessageBox.Show("Not a listbox")
End If
End Sub
Similar to the above but without assertion where assertion should have been used if another control might be sharing the Button Click event.
Code:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Try
DirectCast(sender, ListBox).Items.Clear()
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
-
Feb 10th, 2012, 01:59 PM
#9
Re: Beginner: TRY and CATCH fonctions nothing catches
I was going to suggest what you ended up figuring out for yourself. If you catch only exceptions of a certain type, then any other exceptions raised will not be caught. Therefore, in your initial post, you were catching exceptions of type FormatException, which would miss InvalidCastExceptions, unless those happen to be FormatExceptions (I doubt they are, but I haven't looked it up). So catch the exceptions that are as specific as you can, but not more specific. Sometimes, that's just ex As Exception (which catches all of them). Quite often, catching Exception is good enough, because there simply isn't anything more that you can do if you know that the exception is type A rather than type B. If your actions are going to be the same regardless of the exception type, then why bother catching a specific error?
If so, when using TRY/Catch do you have to only include your TRY and Catch between the required variables in order to trigger the Exception wanted, keep in mind that I am experimenting with the function at this time.
I'm not sure what this means, but I think the answer is NO regardless of what you mean. One thing to remember about exception handling is that it is EXPENSIVE to catch exceptions. Just having the handler in there isn't going to cost any time, but if an exception is thrown, catching that exception is among the slowest things you can do. Therefore, you should ONLY catch real exceptions. What I mean by that is that if you can test for something rather than using exception handling, then you should always do so. Leave exception handling for exceptional situations, which are situations that you can't test for, and can't predict. For instance, no matter how carefully you test, a database or file may not exist at the time you try to read or write to it, so you should always have database and file operations wrapped in exception handling. On the other hand, if you are converting a string into a number, you should never use exception handling, because you can always use TryParse to perform the conversion, and TryParse won't throw an exception.
So don't try to force exceptions to happen. I realize that you are doing this particular exercise to try out exception handling, so for this you want to force exceptions to happen, but realize that in the normal course of action, you wouldn't do things this way. Normally, you'd use TryParse and never throw an exception, so there would be no need for the exception handler.
My usual boring signature: Nothing
 
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|