Results 1 to 9 of 9

Thread: Beginner: TRY and CATCH fonctions nothing catches

  1. #1

    Thread Starter
    New Member mrspock3333's Avatar
    Join Date
    Feb 2012
    Posts
    4

    Question 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:
    1. Try
    2.          monthlyInvestmenmt = convert.ToDecimal(txtMonthlyInvestment.Text)
    3.          YearlyInterestRate = Convert.ToDecimal(txtInterestRate.Text)
    4.          years = convert.ToInt32(txtYears.Text)
    5. Catch ex As FormatException
    6.          messageBox.Show("A format exception has occurred. Plse check all _
    7.          entries.")
    8.  
    9. 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:
    1. Try
    2. Catch ex As Exception
    3.     If txtCurrValue.Text = "" Or txtRate.Text = "" Or txtPeriods.Text = ""
    4.          Then MessageBox.Show("Plse ensure all required field are complete")
    5.          Exit Sub
    6.     End If
    7.     Else
    8.          dblRate = TxtRate.Text
    9.     MessageBox.Show(ex.Message & vbCrLf & vbCrLf & ex.StrackTrace, _
    10.     ex.GetType.ToString)
    11. 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.

  2. #2
    Hyperactive Member mbutler755's Avatar
    Join Date
    May 2008
    Location
    Peoria, AZ
    Posts
    417

    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!
    Regards,

    Matt Butler, MBA, BSIT/SE, MCBP
    Owner, Intense IT, LLC
    Find us on Facebook
    Follow us on Twitter
    Link up on LinkedIn
    mb (at) i2t.us

    CODE BANK SUBMISSIONS: Converting Images to Base64 and Back Again

  3. #3
    I don't do your homework! opus's Avatar
    Join Date
    Jun 2000
    Location
    Good Old Europe
    Posts
    3,863

    Re: Beginner: TRY and CATCH fonctions nothing catches

    Welcome to VBForums
    Quote Originally Posted by mrspock3333 View Post
    ... 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!

  4. #4
    PowerPoster boops boops's Avatar
    Join Date
    Nov 2008
    Location
    Holland/France
    Posts
    3,201

    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

  5. #5

    Thread Starter
    New Member mrspock3333's Avatar
    Join Date
    Feb 2012
    Posts
    4

    Re: Beginner: TRY and CATCH fonctions nothing catches

    Thank you Opus for your welcome to the forum. This is great!

  6. #6

    Thread Starter
    New Member mrspock3333's Avatar
    Join Date
    Feb 2012
    Posts
    4

    Re: Beginner: TRY and CATCH fonctions nothing catches

    Thank you all, mbutler755 I will review my code, thanks.

  7. #7

    Thread Starter
    New Member mrspock3333's Avatar
    Join Date
    Feb 2012
    Posts
    4

    Question 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!

  8. #8
    Karen Payne MVP kareninstructor's Avatar
    Join Date
    Jun 2008
    Location
    Oregon
    Posts
    6,713

    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

  9. #9
    Super Moderator Shaggy Hiker's Avatar
    Join Date
    Aug 2002
    Location
    Idaho
    Posts
    40,106

    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
  •  



Click Here to Expand Forum to Full Width