What are the reasons Process.HasExited can throw InvalidOperationException?

Robert Davis picture Robert Davis · Apr 8, 2010 · Viewed 11k times · Source

I'm seeing a System.Diagnostics.Process.HasExited method throw an InvalidOperationException, but the message text property is not terribly useful as to why it was thrown. Under what conditions does this exception get thrown?

Answer

lmat - Reinstate Monica picture lmat - Reinstate Monica · Sep 27, 2010

I'm seeing the same message. It can happen if you do this:

System.Diagnostics.Process proc = new System.Diagnostics.Process();
proc.StartInfo.FileName = "trash filename here.exe";
try
{
    proc.Start();
}
catch { }//proc should fail.
try
{
    if (proc.HasExited)
    {
        //....
    }
}
catch (System.InvalidOperationException e)
{
    //cry and weep about it here.
}

If proc.Start() failed above, you should get to cry and weep section, too. So, if you catch after proc.Start() be sure to catch at proc.HasExited (and MANY other of the System.Diagnostics.Process Methods.