I'm looking to use Process.Start() to launch an executable, but I want to continue program execution regardless of whether the executable succeeds or fails, or whether Process.Start() itself throws an exception.
I have this:
myProcess.StartInfo.UseShellExecute = false;
// You can start any process, HelloWorld is a do-nothing example.
myProcess.StartInfo.FileName = "C:\\HelloWorld.exe";
myProcess.StartInfo.CreateNoWindow = true;
myProcess.Start();
I know you can add this into try catch
try
{
myProcess.StartInfo.UseShellExecute = false;
// You can start any process, HelloWorld is a do-nothing example.
myProcess.StartInfo.FileName = "C:\\HelloWorld.exe";
myProcess.StartInfo.CreateNoWindow = true;
myProcess.Start();
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
Try catch version will not fail if file not found? How to go with other exception like InvalidOperationException Win32Exception ObjectDisposedException
The goal is just to continue with the code if this fail...
Thanks a lot!
catching exceptions should be reserved for the eventualities you expect to never happen but could possibly happen. instead you can try checking if the file exists first
var filePath = @"C:\HelloWorld.exe";
if(File.Exists(filePath))
{
myProcess.StartInfo.UseShellExecute = false;
// You can start any process, HelloWorld is a do-nothing example.
myProcess.StartInfo.FileName = filePath ;
myProcess.StartInfo.CreateNoWindow = true;
myProcess.Start();
}
Edit
If you want to be extra cautious, you could always use the try catch also but catch the specific exceptions.
try
{
//above code
}
catch(Win32Exception)
{
}
Edit2
var path = new Uri(
Path.Combine((System.Reflection.Assembly.GetExecutingAssembly().CodeBase)).LocalPath,
"filename.exe"));
Final edit
When an exception is caught, your program enters the catch block to allow you to act accordingly, most programs tend to include some kind of error logging into this so this error/bug can be rectified if possible. It may be worth for the time being you just including a message to let the user know something unexpected happened
catch(Win32Exception)
{
MessageBox.Show(this, "There was a problem running the exe");
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With