'index was outside the bounds of the array' exception handling error

I am using the below code to find the base address of a running process. It's within a timer control for other purposes. If the target process is not running I want to display "Process is not running" in the label text, but keep checking for the running process and when/if found continue with the next code block. I have tried a few ways I thought would work, such as a 'try' with exception handling, but the form I am using to hold the label just freezes, I am quit new to c#. Here is the code,

private void timer1_Tick(object sender, EventArgs e)
    {
        #region BaseAddress
        Process[] test = Process.GetProcessesByName("process");
        int Base = test[0].MainModule.BaseAddress.ToInt32();
        #endregion
        //Other code
     }

The exception when run is: "IndexOutOfRange exception was unhandled" - Index was outside the bounds of the array. Hopefully someone can help. Thanks.

Answers


Rather than use a try–catch block to handle the error, you should check whether the process was found before trying to access it:

private void timer1_Tick(object sender, EventArgs e)
{
    #region BaseAddress
    Process[] test = Process.GetProcessesByName("process");
    if (test.Any())
    {
        // Process is running.
        int Base = test[0].MainModule.BaseAddress.ToInt32();
        // Perform any processing you require on the "Base" address here.
    }
    else
    {
         // Process is not running.
         // Display "Process is not running" in the label text.
    }
    #endregion
    //Other code
 }

private void timer1_Tick(object sender, EventArgs e)
    {
        #region BaseAddress
        Process[] test = Process.GetProcessesByName("process");
        if (test.Length > 0)
        {
            int Base = test[0].MainModule.BaseAddress.ToInt32();
        }
        else
        {
            myLabel.Text = "Process is not running";
        }
        #endregion
        //Other code
     }

I think that the Process with the name "process" does not exist. You need to give a real processname. So the array does not contain any elements. Try debugging to see if the array contains any elements and add error handling or a verification that the array length is higher than 0 before doing the second line of your code.


Need Your Help

Primefaces SubTable within subTable

primefaces datatable

I am trying to build a primefaces datatable which has multiple subtables.