locked
Correct use of Try Catch RRS feed

  • Question

  • Hi,
    I have several subs that run processes. I'm using the try catch to catch errors. Am I using it correctly? I mean is the try catch in the correct place in the code? I've seen other examples where the try is started at the beginning before the Dim statement. I'll post my code, then below it I'll post how I've seen it done in other examples.

    Private Sub btnSystemInfo_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSystemInfo.Click
            Dim pSysInfo As New Process
            Dim strSysComputer As String
            strSysComputer = txtSystemInfo.Text
            If txtSystemInfo.Text = "" Then
                MsgBox("You must enter a computer name")
                txtSystemInfo.Focus()
                Exit Sub
            End If
            pSysInfo.StartInfo.FileName = "cmd.exe"
            pSysInfo.StartInfo.Arguments = " /k systeminfo.exe /s " & strSysComputer
            Try
                pSysInfo.Start()
            Catch ex As Exception
                MessageBox.Show(ex.Message)
            End Try
        End Sub


    Private Sub btnSystemInfo_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSystemInfo.Click
            Try
                Dim pSysInfo As New Process
                Dim strSysComputer As String
                strSysComputer = txtSystemInfo.Text
                If txtSystemInfo.Text = "" Then
                    MsgBox("You must enter a computer name")
                    txtSystemInfo.Focus()
                    Exit Sub
                End If
                pSysInfo.StartInfo.FileName = "cmd.exe"
                pSysInfo.StartInfo.Arguments = " /k systeminfo.exe /s " & strSysComputer
    
                pSysInfo.Start()
            Catch ex As Exception
                MessageBox.Show(ex.Message)
            End Try
        End Sub
    Friday, April 10, 2009 1:12 PM

Answers

  • i dont think so brainWasher, i been through it before, Catch ex As Exception is not going to work if try to access file that is proctected. my searching program always crash everytime i try to search for directory that is corrupted, until i used different exception.

    kaymaf


    I hope this helps, if that is what you want, just mark it as answer so that we can move on
    • Marked as answer by Gene Magerr Friday, April 10, 2009 4:37 PM
    Friday, April 10, 2009 3:57 PM
  • Sorry for being a bit unspecific here. In that case you might have an exception that does not derive from the Exception base class. But in you case you can still catch it by using a catch block without a filter:

    Try
    ...
    Catch
    ...
    Finally
    ...
    End Try

    The "ex as Exception" part in the catch line does not need to be written.

    For further information about exception handling, you can also read http://msdn.microsoft.com/en-us/library/8a9f2ew0(VS.80).aspx

    But I think that is a bit too much for Gene's original question ;)

    Please mark the post as answer if solved and maybe post the final solution for others
    • Edited by BrainWasher Friday, April 10, 2009 4:15 PM .
    • Marked as answer by Gene Magerr Friday, April 10, 2009 4:37 PM
    Friday, April 10, 2009 4:14 PM
  • @kay -  Use TextBoxN.Select().    Try reading the documentation, both about Select and Focus.

    http://msdn.microsoft.com/en-us/library/7wt11hea.aspx


    http://msdn.microsoft.com/en-us/library/system.windows.forms.control.focus.aspx

    And here is the reference for Try-Catch again http://msdn.microsoft.com/en-us/library/seyhszts(VS.71).aspx
    Looking for work - Zip 65101 http://www.vbforums.com/showthread.php?t=552774
    • Proposed as answer by dbasnett Friday, April 10, 2009 11:28 PM
    • Marked as answer by Gene Magerr Saturday, April 11, 2009 12:18 AM
    Friday, April 10, 2009 11:21 PM

All replies

  • I think it is more a matter of form.  Here is an MSDN reference you might want to read  http://msdn.microsoft.com/en-us/library/seyhszts(VS.71).aspx
    Looking for work - Zip 65101 http://www.vbforums.com/showthread.php?t=552774
    Friday, April 10, 2009 1:36 PM
  •  it depends on the type of error you want to catch, someytimes Catch ex As Exception does not do what you expect. So there many exceptions you can use but you have to know what kind of error that may occurs. For your example, if systeminfo.exe is missing, it will throw Catch ex As FileNotFoundException. Also, if strSysComputer is nothing, it throws Catch ex As ArgumentNullException 

    Catch
    ex As Exception
    Catch ex As ArgumentOutOfRangeException 
    Catch ex As DriveNotFoundException 
    Catch ex As FileNotFoundException 
    Catch ex As ArgumentNullException
    Catch ex As UnauthorizedAccessException

    kaymaf

    I hope this helps, if that is what you want, just mark it as answer so that we can move on
    • Edited by kaymaf Friday, April 10, 2009 3:29 PM incomplete
    Friday, April 10, 2009 3:22 PM
  • It is not only a matter of form, it is also a matter of what erros you want to catch. In the second example, you will catch all errors that occur. So you are more on the safe side.
    For instance, if for any reason the txtSystemInfo.Focus() should fail, you would not catch the exception in the first example.

    Kaymaf's hint is only correct if you want to treat different exceptions in a different way. In the end Catch ex as Exception will catch them all. If you want to do something if a file was not found and something else for any other exception, you could use both (Catch ex As FileNotFoundException and Catch ex as Exception), which allows you to treat differnt exceptions differently.

    So to summarize: usually the second example is the safer approach, but you don't need to put code into the TRY block if no exception can occur at runtime (like DIMs) or if you deliberately do not want to catch exceptions (eg for nested functions, where the exception is caught in the calling function).

    Any questions, just post back ;)

    Please mark the post as answer if solved and maybe post the final solution for others
    Friday, April 10, 2009 3:29 PM
  • i dont think so brainWasher, i been through it before, Catch ex As Exception is not going to work if try to access file that is proctected. my searching program always crash everytime i try to search for directory that is corrupted, until i used different exception.

    kaymaf


    I hope this helps, if that is what you want, just mark it as answer so that we can move on
    • Marked as answer by Gene Magerr Friday, April 10, 2009 4:37 PM
    Friday, April 10, 2009 3:57 PM
  • Sorry for being a bit unspecific here. In that case you might have an exception that does not derive from the Exception base class. But in you case you can still catch it by using a catch block without a filter:

    Try
    ...
    Catch
    ...
    Finally
    ...
    End Try

    The "ex as Exception" part in the catch line does not need to be written.

    For further information about exception handling, you can also read http://msdn.microsoft.com/en-us/library/8a9f2ew0(VS.80).aspx

    But I think that is a bit too much for Gene's original question ;)

    Please mark the post as answer if solved and maybe post the final solution for others
    • Edited by BrainWasher Friday, April 10, 2009 4:15 PM .
    • Marked as answer by Gene Magerr Friday, April 10, 2009 4:37 PM
    Friday, April 10, 2009 4:14 PM
  • It is not only a matter of form, it is also a matter of what erros you want to catch. In the second example, you will catch all errors that occur. So you are more on the safe side.
    For instance, if for any reason the txtSystemInfo.Focus() should fail, you would not catch the exception in the first example.

    Kaymaf's hint is only correct if you want to treat different exceptions in a different way. In the end Catch ex as Exception will catch them all. If you want to do something if a file was not found and something else for any other exception, you could use both (Catch  ex  As  FileNotFoundException and Catch ex as Exception ), which allows you to treat differnt exceptions differently.

    So to summarize: usually the second example is the safer approach, but you don't need to put code into the TRY block if no exception can occur at runtime (like DIMs) or if you deliberately do not want to catch exceptions (eg for nested functions, where the exception is caught in the calling function).

    Any questions, just post back ;)

    Please mark the post as answer if solved and maybe post the final solution for others
    If it is not a matter of form, then your entire program should be in a Try-Catch block because there isn't a program that might not have some sort of error, like Out of Memory, which may be caused by some other program.  NORMALLY, the Try - Catch surrounds statements that may cause an error, such as Process.Start.  I can't think of a reason why .Focus would fail(.Focus should not be used, it should be .Select).  The first example given by the OP would be what you normally see.

    Looking for work - Zip 65101 http://www.vbforums.com/showthread.php?t=552774
    Friday, April 10, 2009 6:54 PM
  • Thanks dbasnett
    I changed all of the .focus to .select what's the difference?
    Friday, April 10, 2009 7:20 PM
  • From MSDN "Focus is a low-level method intended primarily for custom control authors. Instead, application programmers should use the Select method or the ActiveControl property for child controls, or the Activate method for forms."

    I hope you had a chance to read the Best Practices from MSDN concerning Try-Catch.
    Looking for work - Zip 65101 http://www.vbforums.com/showthread.php?t=552774
    Friday, April 10, 2009 7:27 PM
  • why u change it? when you set your Textbox to focus, is ready for an input from the user, select mean to highlight the text in the textbox. 
    kaymaf
    I hope this helps, if that is what you want, just mark it as answer so that we can move on
    Friday, April 10, 2009 7:39 PM
  • I'm not entirely new to VB, but I am still learning and will try just about anything. As a matter of fact, i enjoy trying everything. If the select works and is the recommended way to do it, i don't have a problem changing it. If .focus is better, that's cool too.
    Friday, April 10, 2009 8:20 PM
  • @kay -  Use TextBoxN.Select().    Try reading the documentation, both about Select and Focus.

    http://msdn.microsoft.com/en-us/library/7wt11hea.aspx


    http://msdn.microsoft.com/en-us/library/system.windows.forms.control.focus.aspx

    And here is the reference for Try-Catch again http://msdn.microsoft.com/en-us/library/seyhszts(VS.71).aspx
    Looking for work - Zip 65101 http://www.vbforums.com/showthread.php?t=552774
    • Proposed as answer by dbasnett Friday, April 10, 2009 11:28 PM
    • Marked as answer by Gene Magerr Saturday, April 11, 2009 12:18 AM
    Friday, April 10, 2009 11:21 PM
  • Thanks for the links I'm reading now.
    Saturday, April 11, 2009 12:18 AM