Try...Catch statement Question

I have a Try...Catch statement that contains 12 Operations inside it. On the catch I want to display a msgbox that tells exactly which operations failed. I was looking through the exception methods and couldn't find one that worked. All of the methods provided relative information but nothing specific.

The reason I want to pinpoint exactly which operations failed is so that the user can email the error message to me and when I get it I will know exactly how to fix it.

Thanks.




Answer this question

Try...Catch statement Question

  • Artyom

    Yeah, that was my original setup. I was just wondering if I could use less code. I'm trying to keep my code as clean as possible.


  • Blair Hall

    You'll have to keep track of that yourself.



  • Rajaraman Soundararajan

    By best practices it generally is considered cleaner to have smaller methods (Plus smaller methods get certain optimization benefits by the CLR JIT compiler such as inlining). However, the stack trace should still tell you where the exception originated. If the 12 operations aren't all calls to the same methods then it should be easy to surmize where in the code the error originated. I do however have to agree that you MAY want to consider refactoring (though there are scenarios where one larger method makes plenty of sense).

  • selotz

    Well, what I am doing is setting the text of about 12 different textboxes with values from a file. If a value doesn't work, because the file was incorrectly modified, then the exception will be thrown.

    That's the reason they are all in one try statement. They all pretty much do the same thing.



  • JoseMiguel

    you use a function, you say

    Excellent

    The solution is to throw your own exceptions. In the function that sets the value of the trackbar to equal the text in the textbox verify the number. Use Double.TryParse() (Or Integer.TryParse if you're confident about the range) in your function. If TryParse returns false the text could not be converted to a number. Throw your own exception and include information about which textbox failed. ApplicationException might work for this but you might be better of extending it in your own class.

    There are times where you want to catch exceptions and times where you want them to bubble up. There are also times where you want to want to let called code throw its own exceptions and times where you can predict them and you'd rather throw them yourself.



  • nokushi0

    No, you can't. Blairs code will give you what is possible, which is no more granular than the scope of your try/catch statement.

    If I need to do something like this, I create a progress string, and set it to tell me where within an operation I am. Then I write that string to my log in an error. I only do this when I know there is a problem within a specific block on a client machine that I cannot replicate.



  • Charlie Babbage

    I am using a trackbar to make sure that the vlaue in the text is only numeric and resides between two numbers (min and max of the trackbar). Using the trackbar makes this simple. I use a function to set the value of the trackbar to equal the text in the textbox. Obviously if the text contains anything but numbers an exception is thrown. This also allows me to make the textbox allow only certain ranges of numbers by setting the min and max values of the trackbar.

    So, when I set the text of all the textboxes at once, it calls my function to set the trackbar to the same value, and if it fails then the exception is thrown. But, since there are many textboxes and more than one of them can fail, it would be nice to know which one failed.

    I think I will probably use a seperate try statement for each textbox, unless anybody con figure out a different way.


  • trident

    Is there a way to show information like a breakpoint shows

    For example my breakpoint details say: At Form1.vb, line 129 character 13 ('Char1_Read', line 25)

    I want details like that.



  • LuckyStarfo

    Ok, I got my statement to work. Now, another problem has surfaced. I know how to do something if an exception is throw but how would I do something only if no exception is thrown. It seems that when the exception is thown (I make a msgbox appear) and I click ok to close the msgbox it still proceeds with the rest of the function.

    This is what I want my statement to do: show a msgbox when an exception is thrown and set a variable if an exception is not thrown but only if an exception is not thrown. How would I do this



  • lvandiest

    Hey Troy. . . Lets go an entirely different direction!!!

    Lets let the wonderful Windows.Forms namespace work for us!!!

    play along with me -

    create a VB windows application

    drop three text boxes on Form1 -  TextBox1, TextBox2. TextBox3

    drop an Error Provider on Form1 - ErrorProvider1

    drop two buttons on Form1

    The error provider is a control extender that adds properties to all the controls. The important one is Error on ErrorProvider1

    put this code in the Form1.vb

    Public Class Form1
        Protected Overrides Sub OnLoad(ByVal e As System.EventArgs)
            Button1.Enabled =
    True
            Button2.Enabled = False
            Button1.Text = "Load Data"
            Button2.Text = "Validate"
            Button1.CausesValidation = False
            Button2.CausesValidation = False
            Me.CausesValidation = False
            Button1.Focus()
            MyBase.OnLoad(e)
        End Sub

        Private
    Sub Button1_Click(ByVal sender As System.Object, _
                     ByVal e As System.EventArgs) _
                              Handles Button1.Click, Button2.Click
            If sender Is Button1 Then
                LoadData()
            Else
                ValidateText()
            End If
        End Sub
     
        Private
    Sub TextBox1_Validating(ByVal sender As System.Object, _
                          ByVal e As System.ComponentModel.CancelEventArgs) _
                                Handles TextBox1.Validating, _
                                              TextBox2.Validating, _
                                              TextBox3.Validating
            Dim n As Integer
            Dim tb As TextBox = sender
            If Not Int32.TryParse(tb.Text, n) Then _
                    ErrorProvider1.SetError(tb, "Invalid number in " & tb.Name)
        End Sub

        Private
    Sub LoadData()
            Button1.Enabled =
    False
            TextBox1.Text = "ABC"
            TextBox2.Text = "123"
            TextBox3.Text = "DEF"
            Button2.Enabled = True
            Button2.Focus()
        End Sub
      
        Public
    Sub Validatetext()
            Button2.Enabled =
    False
            Me.ValidateChildren()
            Button1.Enabled =
    True
            Button1.Focus()
        End Sub
    End Class

    Compile and run

    In short. . . set the text in the text boxes. ..  then validate the text boxes. .. if validation fails, let the error provider give a visual queue as to what data is not valid. Tooltip on the control now displays the error. No clunky exception handling, either.

    Now, here is the beauty - The form only functions as a presentation, it does no data analysis (well yes, we load the data, and we validate the data here but only for simplicity, in theory that functionality could be "delegated")



  • macupryk

    If I gather correctly you are trying to assertain the offending portion of the input file. If that's the case I would advise including the FileStream position in the error report. If you're sending the report from the application you might also include the whole file. If that's not an option, in the catch block record the current position in the filestream. Close it, reopen it, capture about 10-16 bytes around that position and use the Convert class's ToBase64String method to tranform it into a token the user can record and send to you for analysis.

    Other than that I'd need more info about the type of info you're expecting to catch.



  • Recrehal

    Try
    Throw New Exception("foobar")
    Catch ex As Exception
    Dim s As String = String.Format("Exception Occured: {2}{0}{0}{1}{3}{0}{0}{4}", _
    vbNewLine, vbTab, ex.GetType().ToString(), _
    ex.Message, ex.StackTrace)
    MessageBox.Show(s)
    End Try



  • GenericName1

    Are you trying to avoid empty values in the text boxes If your reading a text file have you considered using regular expressions to check you data before display it in your form. If your text file must be a certain format you can use regular expressions to validate it. It's screaming fast! eg.

    Regex.Match(textfile, "( :Name:\s( <name>[a-zA-z\s]))").Success

    '' Then you can use the values from the RegExp to populate your text boxes.

    txtName.Text = Match.Groups("name").value



  • DogCatFish

    If it were me I would refactor the large method into 12 seperate methods. Each method would be named based on what it does. Then have a try catch in each method and it would be easy to tell which one failed.

  • Try...Catch statement Question